使用 Glide 加载图像时遇到错误:无法在回收的位图上调用 reconfigure()



我收到错误

无法在回收的位图上调用 reconfigure((

使用滑翔库加载图像时。 5次中有1次我收到此错误。图像大小约为 1.5MB。

我使用的是 Glide 的 3.8.0 版。

这是我的转换代码:

public class ScaleToFitWidthHeightTransform extends BitmapTransformation {
int mSize = AppConstants.HEIGHT_TRANSFORM_LIMIT; //1020  
boolean isHeightScale;
public ScaleToFitWidthHeightTransform(Context context) {
super(context);
}
public Bitmap transform(Bitmap source) {
float scale;
int newSize;
int sourceHeight = source.getHeight();
int sourceWidth = source.getWidth();
// If original bitmap height/width is less then the height/width transform limit
// then no need to scale the bitmap, so return the original bitmap
if (sourceHeight < AppConstants.HEIGHT_TRANSFORM_LIMIT && sourceWidth < AppConstants.WIDTH_TRANSFORM_LIMIT) { // Height and width limit is 1020.
return source;
}
Bitmap scalBitmap;
if (sourceHeight > sourceWidth) {
scale = (float) AppConstants.HEIGHT_TRANSFORM_LIMIT / source.getHeight();
newSize = Math.round(source.getWidth() * scale);
scaleBitmap = Bitmap.createScaledBitmap(source, newSize, mSize, true);
} else {
scale = (float) AppConstants.WIDTH_TRANSFORM_LIMIT / source.getWidth();
newSize = Math.round(source.getHeight() * scale);
scaleBitmap = Bitmap.createScaledBitmap(source, mSize, newSize, true);
}
if (scaleBitmap != source) {
source.recycle();
}
return scaleBitmap;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return  transform(toTransform);
}
@Override
public String getId() {
return "com.abc";
}

这是我使用Glide的行

Glide.with(context)
.load(imageUri).asBitmap()
.transform(new ScaleToFitWidthHeightTransform(context))
.placeholder(defaultDrawable)
.error(defaultDrawable)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
BitmapSourceData bitmapSourceData = null;
bitmapSourceData = new BitmapSourceData();
bitmapSourceData.setBitmapSource(getBitmapBytes(resource));
if (imageView != null) {
imageView.setImageBitmap(resource);
}                           
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
Log.e("ABC", "Exception --> " + e.toString());
}); // Here I am getting error printed.

我在网上搜索。它说这是由于使用了回收的位图,但我无法修复它。 那么我做错了什么。?

您在此处回收了位图。

if (scaleBitmap != source) {
source.recycle();
}

别这样。。

另外createScaledBitmap是一个非常繁重的操作,避免使用它。您可以使用画布和矩阵缩放位图。

您不必回收位图。 只需注意您的引用计数即可。 如果不再引用位图,GC 将聚合启动并为您清理它。 这只是一个标志,表明它可以更快地成为 GC。

来自有关回收方法的位图文档:

/** * 释放与此位图关联的本机对象,并清除 * 参考像素数据。这不会同步释放像素数据; * 如果没有其他引用,它只是允许对其进行垃圾回收。 * 位图被标记为"死",这意味着它将引发异常,如果 * getPixels(( 或 setPixels(( 被调用,并且不会绘制任何内容。此操作 * 无法反转,因此只有在您确定没有时才应调用它 * 位图的进一步用途。这是一个高级呼叫,通常需要 * 不调用,因为正常的 GC 进程将在以下情况下释放此内存 * 不再引用此位图。

最新更新