在之前的文章
体验知乎图片框架Matisse中,写到过框架回调了Uri数组,那么如何通过Uri数组来生成这些缩略图或是直接得到图片呢?
//通过路径将图片转化为Bitmap
public static Bitmap GetBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
float scaleWidth = 0.f, scaleHeight = 0.f;
if (width > w || height > h) {
scaleWidth = ((float) width) / w;
scaleHeight = ((float) height) / h;
}
opts.inJustDecodeBounds = false;
float scale = Math.max(scaleWidth, scaleHeight);
opts.inSampleSize = (int) scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
通过这个方法可以获取到bitmap图,但是传入的参数是path地址,所以我们还需要先获得path地址。
public static String getRealPathFromURI(Context mContext, Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
通过这2个方法,我们可以获得图片的真实地址,从而获得bitmap,并且可以调整获取到图片的大小,来生成一张大小合理的缩略图。
当然,有时我们并不想对图片进行裁剪就上传,所以我把此方法改造了一下,只要传入path即可获得原图。
public static Bitmap GetRealBitmap(String path) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, opts);
int width = opts.outWidth;
int height = opts.outHeight;
opts.inJustDecodeBounds = false;
float scale = 1;
opts.inSampleSize = (int) scale;
WeakReference<Bitmap> weak = new WeakReference<Bitmap>(
BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), width, height, true);
}