本地图片转bitmap

在项目中将本地图片显示到imageview时,遇到Bitmap转换问题。原有的convertToBitmap方法可能导致空指针错误。文章提供了两种可行的解决方案:1) 使用compressImageFromFile方法通过设置采样率来压缩图片;2) 使用ImageUtils的asyncLoadImage异步加载图片,并在回调中获取Bitmap。
摘要由CSDN通过智能技术生成

项目中需要用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值