位图解码返回null


final Bitmap b = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);

我遇到了一个null引用错误。

b为null。

为什么?

我在完全相同的问题中遇到的好问题(使用完全相同的文件:)
看起来bitmapfactory.decoderesource与R.Drawable和R.Raw相当完美,但与MIPMAP一起可能是由不同的屏幕分辨率引起的,但这只是一个猜测。
在源头上查看我只能看到解码器调用资源#OpenRawResource(..),文档说:

...资产文件 - 也就是说,它可用于打开可绘制,声音和原始资源;它将在字符串和颜色资源上失败。

我猜MIPMAP文件不被视为原始资源,因为还有其他用于选择密度依赖资源的处理。
因此,您必须指定资源的密度:https://stackoverflow.com/a/41910618/8524651

或快速而肮脏的只需将该文件的副本移至您的原始文件夹。

Kotlin中的解决方案代码(以一种方式决定;)

        val launcherDrawable = ResourcesCompat.getDrawableForDensity(context.resources, R.mipmap.ic_launcher, DisplayMetrics.DENSITY_LOW, context.getTheme());
        var bm = BitmapFactory.decodeResource(context.resources, R.raw.ic_launcher)
        bm = launcherDrawable!!.toBitmap(launcherDrawable.minimumWidth, launcherDrawable.minimumHeight)

这可能会帮助您

 Drawable d = getResources().getDrawable(R.mipmap.imagefile);
 Bitmap b = ((BitmapDrawable)d).getBitmap();

最新更新