位图解码流OutOfMemory异常



我在我的应用程序中使用我自己的Android ViewFlow示例的实现。我正在从网络服务下载加密图像,然后保存在SD卡上。我正在使用viewflow在飞行中解密图像并显示它们。但问题是,当用户开始改变图像太快,它扔给我一个OutOfMemoryException和所有的信息,我发现/测试不适合我的情况。下面是我使用的:

 @Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.image_item, null);
    }
    try {
        File bufferFile = new File(ids.get(position));
        FileInputStream fis   = new FileInputStream(bufferFile);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        CipherInputStream cis = new CipherInputStream(fis, cipher);
        BitmapFactory.Options o = new BitmapFactory.Options();
        final int REQUIRED_SIZE=300*1024;
        //Find the correct scale value. It should be the power of 2.
        int width_tmp= o.outWidth, height_tmp= o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }
        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        Bitmap ops = BitmapFactory.decodeStream(cis,null,o2);
        ((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ops);
        cis.close();
        fis.close();
        System.gc();
    } catch (Exception e) {
        e.printStackTrace();
        ((ImageView) convertView.findViewById(R.id.imgView)).setImageResource(R.drawable.image_unavailablee);
    }
    return convertView;
}

它仍然给我抛出那个异常:

((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ops);

java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=6791KB, Allocated=3861KB, Bitmap Size=26006KB)

有什么办法解决这个问题吗?

只是为了供任何正在处理大型位图的人参考,有一篇文章展示了如何处理这类问题以避免OutofMemory!

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

希望有帮助!

REQUIRED_SIZE应该包含最大尺寸(宽度,高度,以像素为单位),如

  final int REQUIRED_SIZE = 1024; // 1024 pixels wide or long.

在计算比例因子之前,您还错过了将图像边界放入BitmapFactory.Options o的几行。

    //Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(cis, null, o);
    //The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

则使用o.outWidtho.outHeight计算比例因子。对于流的实际解码,您可能需要再次获取cis

更新:

还可以将下列变量作为适配器的成员,并在构造函数中初始化:

SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());

摘自这里:http://www.memofy.com/memofy/show/1008ab7f2836ab7f01071c2dbfe138/outofmemory-exception-when-decoding-with-bitmapfactory

试试这个:

BitmapFactory.Options o = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap bitmapImage = BitmapFactory.decodeFile(path, options);

代替:

BitmapFactory.Options o = new BitmapFactory.Options();
    final int REQUIRED_SIZE=300*1024;

因此,在使用BitmapFactory.decodeFile()之前,创建一个16kb的字节数组,并在解码过程中将其传递给临时存储。

希望有帮助!参考:加载图像到位图对象时出现奇怪的内存不足问题

我一次又一次地遇到同样的问题。

这是我的代码,可能有点夸张,但我不得不这样做,因为不同的相机大小,分辨率等,但你必须调整它到你的需要。

            BitmapFactory.Options imageOptions = new BitmapFactory.Options();
        imageOptions.inJustDecodeBounds = true;
        ByteArrayInputStream imageByteArrayInputStream = new ByteArrayInputStream(data);
        BitmapFactory.decodeStream(imageByteArrayInputStream, null, imageOptions);
        System.gc();
        // Decode frame size
        BitmapFactory.Options frameOptions = new BitmapFactory.Options();
        frameOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), selectedFrameResourceID, frameOptions);
        System.gc();
        // Scale factor for pre scaling
        int preScaleFactor = 1;
        if (imageOptions.outWidth > frameOptions.outWidth || imageOptions.outHeight > frameOptions.outHeight) {
            preScaleFactor = Math.max(imageOptions.outWidth / frameOptions.outWidth, imageOptions.outHeight / frameOptions.outHeight);
        }
        // Decode with inSampleSize
        BitmapFactory.Options scaleOptions = new BitmapFactory.Options();
        scaleOptions.inSampleSize = preScaleFactor;
        imageByteArrayInputStream = new ByteArrayInputStream(data);
        Bitmap preScaledBitmap = BitmapFactory.decodeStream(imageByteArrayInputStream, null, scaleOptions);
        System.gc();
        Bitmap finalBitmap;
        // Scale factor for precise scaling
        // If the scaled image is not exactly the same size as the frame than resize it precisely
        if (preScaledBitmap.getWidth() != frameOptions.outWidth || preScaledBitmap.getHeight() != frameOptions.outHeight) {
            float scaleFactor = Math.max((float)((float)preScaledBitmap.getWidth() / (float)frameOptions.outWidth), (float)((float)preScaledBitmap.getHeight() / (float)frameOptions.outHeight));
            float scalePercentage = Math.min((float)((float)frameOptions.outWidth / (float)preScaledBitmap.getWidth()), (float)((float)frameOptions.outHeight / (float)preScaledBitmap.getHeight()));
            Matrix matrix = new Matrix();
            matrix.preScale(scalePercentage, scalePercentage);
            // If the capture width for the source is bigger than the actual width of the source, then set is to the max of the actual source width
            int sourceCaptureWidth = (int)(frameOptions.outWidth * scaleFactor);
            if (sourceCaptureWidth > preScaledBitmap.getWidth()) {
                sourceCaptureWidth = preScaledBitmap.getWidth();
            }
            // Same as above but than for the height
            int sourceCaptureHeight = (int)(frameOptions.outHeight * scaleFactor);
            if (sourceCaptureHeight > preScaledBitmap.getHeight()) {
                sourceCaptureHeight = preScaledBitmap.getHeight();
            }
            finalBitmap = Bitmap.createBitmap(preScaledBitmap, 0, 0, sourceCaptureWidth, sourceCaptureHeight, matrix, true);
            preScaledBitmap.recycle();
            preScaledBitmap = null;

希望能有所帮助

使用recycle()。它将释放与此位图关联的本机对象,并清除对像素数据的引用。

 Bitmap ops = BitmapFactory.decodeStream(cis,null,o2);
        ((ImageView) convertView.findViewById(R.id.imgView)).setImageBitmap(ops);
        cis.close();
        fis.close();
        ops.recycle();
        System.gc();

你使用的是哪个版本的Android ?如果您在Honeycomb或更高版本上运行它,您应该能够使用Eclipse内存分析器来查看内存的使用情况。

也就是说,您需要在位图不再需要或不再显示时调用recycle()(这是Sujits答案的问题)。换句话说,如果位图从屏幕上消失,最好是回收()它,然后在它回到视图中时重新加载它。否则,该位图为usi

要做到这一点,在你的ImageView上调用getDrawable(),在你的ImageView上调用setImageDrawable(null),然后将drawable转换为BitmapDrawable并回收其中的位图。

有关位图内存在Android 3.0之前如何工作的更多信息,您可以查看我在此问题上的帖子:http://code.google.com/p/android/issues/detail?id=8488#c80

最新更新