在ACTION_GET_CONTENT系统意图下选择图像后,我试图获取在onActivityResult返回的图像。我正在使用doc的“ setPic()”方法来减小图像大小,但是由于某种原因,使用该方法时我什么也没得到。这是我的Intent,onActivityResulty和setPic()方法-
private void requestPickingPhoto() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_VIDEO_REQUEST_CODE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_VIDEO_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri originalDataUri = data.getData();
cachedLocalImageUri = originalDataUri;
Timber.d("Receive image from: %s", originalDataUri);
mImageSent.setImageURI(cachedLocalImageUri);
setPic(originalDataUri.toString(), mImageSent);
}
}
private void setPic(String imagePath, ImageView destination) {
int targetW = destination.getWidth();
int targetH = destination.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = (int) Math.sqrt(Math.min(photoW/targetW, photoH/targetH));
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
destination.setImageBitmap(bitmap);
}
我的目标是使用从意图中得到的Uri,以大幅降低图像分辨率,以便将其用于大小有限的Firebase云消息传递丰富的通知。
答案 0 :(得分:1)
originalDataUri.toString()
不会提供文件路径。
因此,您不能BitmapFactory.decodeFile(imagePath, bmOptions);
。
相反,一旦您从Uri
打开流,就可以使用BitmapFactory.decodeStream(InputStream is)
:
将您的String imagePath
方法的参数setPic
更改为Uri uri
,而不是
BitmapFactory.decodeFile(imagePath, bmOptions);
执行此操作:
InputStream is = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(is, null, bmOptions);
与方法末尾相同:代替
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
做
Bitmap bitmap = BitmapFactory.decodeStream(is, null, bmOptions);
请注意,您需要有效的Context
。