boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.Output

log日志

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

出错代码

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

代码很简单,BitmapFactory读取图片到Bitmap,然后转成byte,这也是网上搜索到的最常用的方法,但是运行之后就出现了上面空指针的错误,bitmap为空
在这里插入图片描述
在网上找到了这篇文章BitmapFactory.decodeResource为null的处理方法之一,这里所说R.mipmap.ic_launcher是一个vector图片,此代码在4.4上运行正常,但在5.0以上的系统会出现空指针,原因在于此本来方法不能将vector转化为bitmap,而apk编译时为了向下兼容,会根据vector生产相应的png,而4.4的系统运行此代码时其实用的是png资源。这就是为什么5.0以上会报错,而4.4不会的原因

解决办法

private static Bitmap getBitmap(Context context,int vectorDrawableId) {
    Bitmap bitmap=null;
    if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
        Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
        bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawable.draw(canvas);
    }else {
        bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
    }
    return bitmap;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孤独的冥王星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值