如何避免"内存不够的异常&QUOT的;做位图处理的时候? [英] How to avoid "out of memory exception" when doing Bitmap processing?

查看:122
本文介绍了如何避免"内存不够的异常&QUOT的;做位图处理的时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

onPictureTaken ,我要做到以下几点:

In onPictureTaken, I want to do the following:

Bitmap decodedPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.preScale(-1.0f, 1.0f);
Bitmap picture = Bitmap.createBitmap(decodedPicture, 0, 0, decodedPicture.getWidth(), decodedPicture.getHeight(), matrix, false);

View v1 = mainLayout.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap screenshot = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

Bitmap scaledPicture = Bitmap.createScaledBitmap(picture, screenshot.getWidth(), screenshot.getHeight(), true);

Bitmap compos = Bitmap.createBitmap(scaledPicture.getWidth(), scaledPicture.getHeight(), Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(compos);
canvas.drawBitmap(scaledPicture, new Matrix(), null);
canvas.drawBitmap(screenshot, new Matrix(), null);

MediaStore.Images.Media.insertImage(getContentResolver(), compos, "name" , "description");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));

我唯一的要求是,我想救一个高品质的照片......看来我可能要牺牲的。

My only requirement is that I'd like to save a high-quality photo... Seems I might have to sacrifice that.

在我的Nexus 4和较新的设备,这code运行正常,并符合市场预期。但是,在具有更少的内存的旧设备,我跑出来的内存! :(

On my Nexus 4 and newer devices, this code runs fine and as expected. But on older devices that have less memory, I'm running out of RAM! :(

我如何做同样的图像处理,而不针对内存限制跑起来?我并不想给的显示的屏幕上的这些图像,所以解决方案都与一个按比例缩小的图像并不真正适用于此......

How do I do the same image manipulation without running up against the memory limit?? I'm not trying to display these images on screen, so the solutions that have to do with a scaled down image don't really apply here...

推荐答案

您需要阅读的位图与增加样本量。诀窍在于找到不会导致降低分辨率,当你最终缩放图像正确的样本量。我写了一个关于它的博客文章在这里,包括缩放一个很好的实用工具类,

you need to read the bitmap in with an increased sample size. the trick is finding the correct sample size that won't result in reduced resolution when you ultimately scale the image. i wrote a blog entry about it here that includes a nice utility class for scaling,

HTTP://zerocredibility.word$p $ pss.com / 2011/01/27 / Android的位图缩放/

您也许可以简化该类颇有几分根据您的具体需求。

you could probably simplify that class quite a bit depending on your specific needs.

的JIST是读取位图只是大小。计算基于所需的缩放尺寸的最优样本量,阅读位图中使用的样本量,然后精细尺度它正是你想要的大小。

the jist is to read just the size of the bitmap. calculate the optimal sample size based on your desired scaled size, read the bitmap in using that sample size, then fine-scale it to exactly the size you want.

这篇关于如何避免"内存不够的异常&QUOT的;做位图处理的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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