加入大图像时出现 OutOfMemory 错误 [英] OutOfMemory error while joining large images

查看:24
本文介绍了加入大图像时出现 OutOfMemory 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码连接两个图像,但它抛出一个 OutOfMemory 错误,我的图像每个大约 1MB.

I am joining two images using the code below but it throws an OutOfMemory error my images are around 1MB each.

private Bitmap overlayMark(String first, String second)
{
    Bitmap bmp1, bmp2;
    bmp1 = BitmapFactory.decodeFile(first);
    bmp2 = BitmapFactory.decodeFile(second);
    if (bmp1 == null || bmp2 == null)
        return bmp1;

    int height = bmp1.getHeight();
    if (height < bmp2.getHeight())
        height = bmp2.getHeight();

    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth() + bmp2.getWidth(), height,
            Bitmap.Config.ARGB_8888);// Out of memory
    Canvas canvas = new Canvas(bmOverlay);
    canvas.drawBitmap(bmp1, 0, 0, null);
    canvas.drawBitmap(bmp2, bmp1.getWidth(), 0, null);
    bmp1.recycle();
    bmp2.recycle();
    return bmOverlay;
}

更新:我尝试了以下两个答案,但仍然无法创建如此大尺寸的位图,问题是生成的位图尺寸太大,大约 2400x3200,因此内存不足.

Update: I tried below two answers but it still not allwoing me to create bitmap of such big size the problem is that the resultant bitmap is too large in size around 2400x3200 so its going out of memory.

如何在不耗尽内存的情况下加入大图像?

推荐答案

无需将图像加载到内存中,您就可以使用 inJustDecodeBounds 获取图像的大小.Bitmap 返回 null,但所有参数都已设置.您可以相应地缩小图像.

Without loading the image into memory, you CAN get the size of the image, using inJustDecodeBounds. The Bitmap returns null, but all the parameters are set. You can scale down the image accordingly.

如果您的 JPEG 图像每个是 1 MiB,则转换为 BMP 确实会占用大量内存.您可以通过图像的尺寸轻松计算其 BMP 等效值.转换这么大的图片估计确实会崩溃.Android 将其应用程序限制为 16 MiB 虚拟机.

If your JPEG images are 1 MiB each, conversion to a BMP will take a lot of memory indeed. You can easily calculate its BMP equivalent by the dimensions of the image. Conversion of such a large image is expected to crash indeed. Android limits its apps to 16 MiB VM only.

也使用 RGB_565 而不是 ARGB_8888.

Also use RGB_565 instead of ARGB_8888.

所以你唯一的解决办法是:(a) 使用 BitmapFactory.Options.inSampleSize 缩小图像或者(b) 使用没有 16 MiB 限制的 Android NDK.

So your only solution is: (a) To use BitmapFactory.Options.inSampleSize to scale down the image or (b) Use Android NDK where the 16 MiB limit isn't there.

这篇关于加入大图像时出现 OutOfMemory 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆