我正在使用以下代码here http://voidcanvas.com/whatsapp-like-image-compression-in-android/。我想压缩图像。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
从相机、图库和照片中选择图像后,我根据操作系统类型和设备型号在不同设备中获得不同类型的路径。喜欢:
1) /存储/模拟/0/Android/数据/...
2)/raw//存储/模拟/0/mb/1511172993547.jpg
3)/2/1/content://media/external/images/media/11647/ORIGINAL/NONE/486073582
如果路径类似于第一个网址,则此代码可以正常工作。但如果我得到其他类型的图像,则 BitmapFactory.decodeFile() 给出 null。
有没有办法在所有类型的设备和操作系统版本中压缩图像。
UPDATE :
打开选择器:
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;
}