相机内存消耗

时间:2012-06-29 22:55:41

标签: android memory-management camera

我正在通过Android相机API拍照:

为了计算某些图像处理的可用内存,我想检查图像是否适合内存。 我正在使用这些功能:

   /**
     * Checks if a bitmap with the specified size fits in memory
     * @param bmpwidth Bitmap width
     * @param bmpheight Bitmap height
     * @param bmpdensity Bitmap bpp (use 2 as default)
     * @return true if the bitmap fits in memory false otherwise
     */
    public static boolean checkBitmapFitsInMemory(long bmpwidth,long bmpheight, int bmpdensity ){
        long reqsize=bmpwidth*bmpheight*bmpdensity;
        long allocNativeHeap = Debug.getNativeHeapAllocatedSize();

        if ((reqsize + allocNativeHeap + Preview.getHeapPad()) >= Runtime.getRuntime().maxMemory())
        {
            return false;
        }
        return true;
    }

    private static long getHeapPad(){
        return (long) Math.max(4*1024*1024,Runtime.getRuntime().maxMemory()*0.1);
    }

问题是:我仍然收到OutOfMemoryExceptions(不在我的手机上,而是来自已下载我的应用的人)

以下代码的最后一行发生异常:

public void onPictureTaken(byte[] data, Camera camera) {
        Log.d(TAG, "onPictureTaken - jpeg");
        final byte[] data1 = data;
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inSampleSize = downscalingFactor;
        Log.d(TAG, "before gc");
        printFreeRam();
        System.gc();
        Log.d(TAG, "after gc");
        printFreeRam();
        Bitmap photo = BitmapFactory.decodeByteArray(data1, 0, data1.length, options);

通过checkBitmapFitsInMemory()方法选择downscalingFactor。 我是这样做的:

 for (downscalingFactor = 1; downscalingFactor < 16; downscalingFactor ++) {
    double width = (double) bestPictureSize.width / downscalingFactor;
    double height = (double) bestPictureSize.height / downscalingFactor;
    if(Preview.checkBitmapFitsInMemory((int) width, (int) height, 4*4)){ // 4 channels (RGBA) * 4 layers
        Log.v(TAG, "  supported: " + width+'x'+height);
        break;
    }else{
        Log.v(TAG, "  not supported: " + width+'x'+height);
    }
   }

任何人都知道为什么这种方法如此错误?

1 个答案:

答案 0 :(得分:0)

尝试更改此内容:

Bitmap photo = BitmapFactory.decodeByteArray(data1, 0, data1.length, options);

到此:

Bitmap photo = BitmapFactory.decodeByteArray(**data**, 0, data.length, options);