Attempt to invoke virtual method int android.graphics.Bitmap.getWidth() on a null object

本文针对Android Q版本中BitmapFactory.decodeFile导致的getWidth()返回null的问题,提供了适用于不同Android版本的解决方案,包括使用ContentResolver和ParcelFileDescriptor处理高版本系统,确保图片加载的兼容性和正确性。

公司之前老项目升级:之前使用:BitmapFactory.decodeFile(path,myOptions);一直很好的,今天突然 ‘int android.graphics.Bitmap.getWidth()’ on a null 一直报null。
奇怪的是,28一下手机正常,29不正常。马上想到是Android Q的特性。

 BitmapFactory.Options myOptions = new BitmapFactory.Options();
        myOptions.inJustDecodeBounds=true;
        myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
        this.mBitmap=BitmapFactory.decodeFile(path,myOptions);

在此之前,还搜索看了不少,不是说读写权限没给,就是图片太大,其实压根都不是。
解决代码如下:
//java

 if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.P){
            this.mBitmap=BitmapFactory.decodeFile(path,picOptions);
        }else{
            ContentResolver contentResolver=getContext().getContentResolver();
            ParcelFileDescriptor fd = null;
            try {
                fd = contentResolver.openFileDescriptor(Uri.parse(path), "r");
                if (fd != null) {
                    this.mBitmap = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
                    fd.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

kotlin:

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            this.mBitmap = BitmapFactory.decodeFile(path, picOptions)
        } else {
            val contentResolver: ContentResolver = getContext().getContentResolver()
            var fd: ParcelFileDescriptor? = null
            try {
                fd = contentResolver.openFileDescriptor(Uri.parse(path), "r")
                if (fd != null) {
                    this.mBitmap = BitmapFactory.decodeFileDescriptor(fd.fileDescriptor)
                    fd.close()
                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

另外在Android Q上drawbitmap要使用先绘制矩形, canvas.drawBitmap(bitmap,null,rect,null);的方案。若直接使用这个API:图片会变形。

 public void drawBitmap(@NonNull Bitmap bitmap, float left, float top, @Nullable Paint paint) 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值