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;
}