项目中需要用imageview显示本地图片,参考别人的博客。
网上有一个方法,试了下,会报空指针:如下
public Bitmap convertToBitmap(String path, int w, int h) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 设置为ture只获取图片大小
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 weak = new WeakReference(BitmapFactory.decodeFile(path, opts));
return Bitmap.createScaledBitmap(weak.get(), w, h, true);
}
多试几次就会报错。
以下两个方法可以用:
1.
/**
* 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式
* 特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩
* @param srcPath
* @return
*/
public static Bitmap compressImageFromFile(String srcPath, float pixWidth, float pixHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;// 只读边,不读内容
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, options);
options.inJustDecodeBounds = false;
int w = options.outWidth;
int h = options.outHeight;
int scale = 1;
if (w > h && w > pixWidth) {
scale = (int) (options.outWidth / pixWidth);
} else if (w < h && h > pixHeight) {
scale = (int) (options.outHeight / pixHeight);
}
if (scale <= 0)
scale = 1;
options.inSampleSize = scale;// 设置采样率
options.inPreferredConfig = Bitmap.Config.ARGB_8888;// 该模式是默认的,可不设
options.inPurgeable = true;// 同时设置才会有效
options.inInputShareable = true;// 。当系统内存不够时候图片自动被回收
bitmap = BitmapFactory.decodeFile(srcPath, options);
// return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩
// 其实是无效的,大家尽管尝试
return bitmap;
}
2.
imagePath 是图片等本地路径 ,例如 /storage/emulated/0/album_2016-11-23_12:12:11.jpg
Uri targetUri = Uri.fromFile(new File(imagePath));
ImageUtils.asyncLoadImage(this, targetUri, new ImageUtils.LoadImageCallback() {
@Override
public void callback(Bitmap bitmap) {
shareBitmap = bitmap;
}
});
public class ImageUtils {
public static int getMiniSize(String imagePath) {
BitmapFactory.Options options = ne