公司之前老项目升级:之前使用: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)
本文针对Android Q版本中BitmapFactory.decodeFile导致的getWidth()返回null的问题,提供了适用于不同Android版本的解决方案,包括使用ContentResolver和ParcelFileDescriptor处理高版本系统,确保图片加载的兼容性和正确性。

7823

被折叠的 条评论
为什么被折叠?



