Android加载图片到ImageView触发TransactionTooLargeException如何解决
错误诱因
TransactionTooLargeException 出现的核心原因是Android系统的Binder事务缓冲区大小限制为1MB左右,你报错的Parcel大小为1.8MB,超出了限制。触发该问题的具体原因来自两点:
- 你从数据库读取的是未压缩的全尺寸Bitmap,尺寸远大于ImageView的实际显示需求,占用内存过高
- Activity进入后台时系统会自动保存ImageView的状态,会把当前显示的Bitmap打包到SavedInstanceState的Parcel中,过大的Bitmap直接超出了Binder缓冲区限制
修复方案
1. 禁用ImageView的自动状态保存
你每次进入Activity都会主动从数据库加载图片,不需要系统保存ImageView的Drawable状态,直接关闭该功能即可避免状态保存时的Parcel超限问题:
在XML的ImageView标签中添加属性:
android:saveEnabled="false"
也可以在Activity的onCreate方法中添加代码:
binding.imageView3.setSaveEnabled(false);
2. 压缩图片后再加载
不要直接加载全尺寸Bitmap,根据ImageView的实际显示尺寸采样压缩,大幅降低内存占用:
首先修改Activity加载逻辑,等ImageView布局完成后拿到实际宽高再加载图片
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_view); itemCode = getIntent().getStringExtra("itemCode"); db = new ACDatabase(this); ActivityImageViewBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_image_view); binding.imageView3.setContentDescription(itemCode); binding.imageView3.setSaveEnabled(false); // 等待ImageView布局完成,拿到实际显示的宽高 binding.imageView3.post(() -> { int targetW = binding.imageView3.getWidth(); int targetH = binding.imageView3.getHeight(); Bitmap bitmap = db.getItemImage(itemCode, targetW, targetH); if (bitmap != null) { binding.noImageTxt.setVisibility(View.INVISIBLE); binding.imageView3.setImageBitmap(bitmap); } else { binding.imageView3.setVisibility(View.INVISIBLE); } }); binding.setHandler(new MyClickHandler(ImageView.this)); }
然后修改getItemImage方法,增加压缩逻辑,同时补上Cursor、数据库关闭逻辑避免内存泄漏
public Bitmap getItemImage(String itemCode, int targetW, int targetH) { Cursor data = null; SQLiteDatabase database = this.getReadableDatabase(); String[] itemCols = new String[]{"Image"}; try { data = database.query(TABLE_NAME_ITEM, itemCols, "ItemCode = ?", new String[]{itemCode}, null, null, null); if (data.getCount() > 0 && data.moveToNext()) { // 建议直接存Blob格式,不要用Base64,Base64会比原始二进制大33%,徒增开销 byte[] imageBytes = data.getBlob(0); // 如果必须保留Base64存储,就注释上面一行,解开下面一行 // byte[] imageBytes = Base64.decode(data.getString(0), Base64.DEFAULT); // 先解码图片尺寸,不把全图加载到内存 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options); int photoW = options.outWidth; int photoH = options.outHeight; // 计算采样率,压缩到刚好适配ImageView尺寸 int scaleFactor = Math.max(1, Math.min(photoW / targetW, photoH / targetH)); // 按采样率加载压缩后的图片 options.inJustDecodeBounds = false; options.inSampleSize = scaleFactor; options.inPurgeable = true; return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options); } } catch (Exception e) { Log.i("custDebug", e.getMessage()); } finally { // 关闭Cursor和数据库,避免内存泄漏 if (data != null) { data.close(); } database.close(); } return null; }
3. 可选优化
将数据库中图片的存储方式从Base64改为Blob,减少不必要的编解码开销,同时降低存储占用。
内容的提问来源于stack exchange,提问作者Venus Lu
相关产品推荐
相关产品推荐

