gpt4 book ai didi

Android,内存不足转换为黑白

转载 作者:行者123 更新时间:2023-11-29 14:38:30 26 4
gpt4 key购买 nike

当用户触摸某些资源时,我会将它们转换为黑白。我的 Util java 文件中有这个功能:

public static Bitmap convertColorIntoBlackAndWhiteImage(Bitmap orginalBitmap) {
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);

ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(colorMatrix);
Bitmap blackAndWhiteBitmap = orginalBitmap.copy(Bitmap.Config.ARGB_8888, true);

Paint paint = new Paint();
paint.setColorFilter(colorMatrixFilter);

Canvas canvas = new Canvas(blackAndWhiteBitmap);
canvas.drawBitmap(blackAndWhiteBitmap, 0, 0, paint);

return blackAndWhiteBitmap;
}

但有时,在某些设备上我会收到此错误:

java.lang.OutOfMemoryError
at android.graphics.Bitmap.nativeCopy(Native Method)
at android.graphics.Bitmap.copy(Bitmap.java:479)
at com.mygame.util.Util.convertColorIntoBlackAndWhiteImage(Util.java:145)

该函数的第 145 行是

Bitmap blackAndWhiteBitmap = orginalBitmap.copy(Bitmap.Config.ARGB_8888, true);

准确地说,我从其他 stackoverflow 答案中获取了该函数。

发生了什么事?

谢谢

最佳答案

这可能对你有帮助...

public static Bitmap convertColorIntoBlackAndWhiteImage(Bitmap orginalBitmap) {
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);

ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
colorMatrix);
Bitmap blackAndWhiteBitmap = orginalBitmap.copy(
Bitmap.Config.ARGB_8888, true);
// Recycle the Bitmap and free the memory once you copied into new
// Bitmap
orginalBitmap.recycle();
orginalBitmap = null;
// still problem exists call
// System.gc();
// System.gc();

Paint paint = new Paint();
paint.setColorFilter(colorMatrixFilter);

Canvas canvas = new Canvas(blackAndWhiteBitmap);
canvas.drawBitmap(blackAndWhiteBitmap, 0, 0, paint);

return blackAndWhiteBitmap;
}

您似乎正在尝试将图像转换为灰色。试试这个……

    public static Bitmap toGrayBitmap(Bitmap bitmap) {
if (bitmap == null || bitmap.isRecycled()) {
return null;
}
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();

Bitmap canvasBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
canvas.drawARGB(0, 0, 0, 0);

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(
colorMatrix);
paint.setColorFilter(filter);

canvas.drawBitmap(bitmap, 0, 0, paint);
bitmap.recycle(); // do it if still problem exists

return canvasBitmap;
}

关于Android,内存不足转换为黑白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20918737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com