很多朋友给小编反馈使用方法BitmapFactory.decodeFile转化Bitmap时报错,究竟是什么原因导致错误问题呢?今天通过本文给大家介绍下解决Android BitmapFactory的基本使用问题,感兴趣的朋友一起看看吧
问题描述
使用方法BitmapFactory.decodeFile转化Bitmap时报错:java.lang.RuntimeException: Canvas: trying to draw too large(120422400bytes) bitmap.
解决方案
报错原因:图片转化为Bitmap超过最大值MAX_BITMAP_SIZE
frameworks/base/graphics/java/android/graphics/RecordingCanvas.java
public static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB
/** @hide */
@Override
protected void throwIfCannotDraw(Bitmap bitmap) {
super.throwIfCannotDraw(bitmap);
int bitmapSize = bitmap.getByteCount();
if (bitmapSize > MAX_BITMAP_SIZE) {
throw new RuntimeException(
"Canvas: trying to draw too large(" + bitmapSize + "bytes) bitmap.");
}
}
修改如下
//修改前
Bitmap image = BitmapFactory.decodeFile(filePath);
imageView.setImageBitmap(image);
//修改后
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
File file = new File(filePath);
if (file.exists() && file.length() > 0) {
//获取设备屏幕大小
DisplayMetrics dm = getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
//获取图片宽高
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
//计算缩放比例
int inSampleSize = 1;
if (srcHeight > screenHeight || srcWidth > screenWidth) {
if (srcWidth > srcHeight) {
inSampleSize = Math.round(srcHeight / screenHeight);
} else {
inSampleSize = Math.round(srcWidth / screenWidth);
}
}
options.inJustDecodeBounds = false;
options.inSampleSize = inSampleSize;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imageView.setImageBitmap(bitmap);
}
相关参考:
Android 图片缓存之 Bitmap 详解
https://juejin.cn/post/6844903442939412493
BitmapFactory
https://developer.android.com/reference/android/graphics/BitmapFactory.html
BitmapFactory.options
BitmapFactory.Options类是BitmapFactory对图片进行解码时使用的一个配置参数类,其中定义了一系列的public成员变量,每个成员变量代表一个配置参数。
https://blog.csdn.net/showdy/article/details/54378637
到此这篇关于Android BitmapFactory的基本使用的文章就介绍到这了,更多相关Android BitmapFactory使用内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:解决Android BitmapFactory的基本使用问题
- 作为iOS开发,这道面试题你能答出来,说明你基础很OK! 2023-09-14
- iOS 对当前webView进行截屏的方法 2023-03-01
- Flutter实现底部和顶部导航栏 2022-08-31
- Android MaterialButton使用实例详解(告别shape、selector) 2023-06-16
- Android实现轮询的三种方式 2023-02-17
- 最好用的ios数据恢复软件:PhoneRescue for Mac 2023-09-14
- 详解flutter engine 那些没被释放的东西 2022-12-04
- Android studio实现动态背景页面 2023-05-23
- Android实现监听音量的变化 2023-03-30
- SurfaceView播放视频发送弹幕并实现滚动歌词 2023-01-02
