android從選擇圖片有兩種方法,但是傳回值確不同,本文將指導大家如何統一這兩種方式的傳回值。
//關鍵代碼
@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, 100, 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, 100, 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();
//建立目錄
appPath = new File(Environment.getExternalStorageDirectory(), getPackageName());
if (!appPath.isDirectory()) {
appPath.mkdir();
}
}
經過統一處理之後,傳回值均為圖片的絕對路徑地址。