Android has two ways to choose a picture, but the return value is different, and this article will guide you through how to unify the return values in both ways.
Critical code
@Event (R.id.btnphoto)
private void onbtnphotoclicked (view view) {
Intent Intent = new Intent (Intent.action_pick, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Startactivityforresult (Intent, Config.Constants.CODE_PICK_IMAGE_FROM_PHOTO);
}
@Event (R.id.btncamera)
private void onbtncameraclicked (view view) {
Intent Intent = new Intent (mediastore.action_image_capture);
Startactivityforresult (Intent, Config.Constants.CODE_PICK_IMAGE_FROM_CAMERA);
}
@Override
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
Switch (requestcode) {
Case Config.Constants.CODE_PICK_IMAGE_FROM_CAMERA:
if (data!= null && data.hasextra ("data")) {
Bitmap Bitmap = Data.getparcelableextra ("Data");
Bitmap = Bitmaputil.scale (Bitmap, 640.0f/bitmap.getwidth ());
try {
File path = new file (((MyApplication) getapplication ()). AppPath, Dateutil.format (New Date (), "YYYYMMDDHHMMSS") + ". jpg") ;
FileOutputStream outputstream = new FileOutputStream (path);
Bitmap.compress (Bitmap.CompressFormat.JPEG, OutputStream);
Outputstream.close ();
Intent Intent = new Intent ();
Intent.putextra ("Path", Path.getabsolutepath ());
Setresult (RESULT_OK, intent);
catch (IOException e) {
E.printstacktrace ();
}
}
Finish ();
Break
Case Config.Constants.CODE_PICK_IMAGE_FROM_PHOTO:
if (data!= null) {
Uri uri = Data.getdata ();
Bitmap Bitmap;
Contentresolver contentresolver = Getcontentresolver ();
try {
Bitmap = MediaStore.Images.Media.getBitmap (Contentresolver, URI);
Bitmap = Bitmaputil.scale (Bitmap, 640.0f/bitmap.getwidth ());
File path = new file (((MyApplication) getapplication ()). AppPath, Dateutil.format (New Date (), "YYYYMMDDHHMMSS") + ". jpg") ;
FileOutputStream outputstream = new FileOutputStream (path);
Bitmap.compress (Bitmap.CompressFormat.JPEG, OutputStream);
Outputstream.close ();
Intent Intent = new Intent ();
Intent.putextra ("Path", Path.getabsolutepath ());
Setresult (RESULT_OK, intent);
catch (IOException e) {
E.printstacktrace ();
}
}
Finish ();
Break
Default
Super.onactivityresult (Requestcode, ResultCode, data);
}
}
Bitmaputil.java
public static Bitmap scale (Bitmap Bitmap, float scale) {
Matrix matrix = new Matrix ();
Matrix.postscale (scale, scale);
Return Bitmap.createbitmap (Bitmap, 0, 0, bitmap.getwidth (), Bitmap.getheight (), Matrix, True);
}
MyApplication
Public File AppPath;
@Override
public void OnCreate () {
Super.oncreate ();
Create a table of contents
AppPath = new File (Environment.getexternalstoragedirectory (), Getpackagename ());
if (!apppath.isdirectory ()) {
Apppath.mkdir ();
}
}
After unified processing, the return value is the absolute path address of the picture.