【发布时间】:2018-05-03 13:58:22
【问题描述】:
我正在使用来自here 的以下代码。我想压缩图像。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
从相机、图库和照片中选择图像后,我会根据操作系统类型和设备型号在不同设备中获得不同类型的路径。喜欢:
1) /storage/emulated/0/Android/data/...
2) /raw//storage/emulated/0/mb/1511172993547.jpg
3) /2/1/content://media/external/images/media/11647/ORIGINAL/NONE/486073582
如果路径类似于第一个 url,则此代码工作正常。但是如果我得到其他类型的图像,那么 BitmapFactory.decodeFile() 将给出 null。
有没有办法在所有类型的设备和操作系统版本中压缩图像。
更新:
打开选择器:
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent, 1001);
选择图片后:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri imgUri = Uri.fromFile(new File(data.getData().getPath()));
Bitmap cmpBitmap = ImageUtils.compressUriQuality(OpenWallWeb.this, imgUri);
dlgImageToPost.setImageBitmap(cmpBitmap);
...
}
压缩:
public static Bitmap compressUriQuality(Context mContext, Uri selectedImage) {
InputStream imageStream = null;
Bitmap bmp = null;
try {
imageStream = mContext.getContentResolver().openInputStream(
selectedImage);
bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 50, stream);
if (imageStream != null)
imageStream.close();
stream.close();
stream = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
【问题讨论】:
-
你有图像
Uri,所以打开它的InputStream并使用BitmapFactory解码它 - 你可以使用ContentResolverAPI得到InputStream -
你是想从厨房或任何其他路径获取图像路径???
-
不,不要使用任何“图像路径” - 你只需要
Uri -
感谢您的评论,我会尝试使用 Uri
标签: android bitmap bitmapfactory image-compression