Out of Memory when using compresstojpeg on multiple YuvImage one at a time

梦想的初衷 提交于 2019-12-05 08:35:37
vfranchi

I managed to find a solution for my problem, and it was by not using YuvImage class. I guess something is wrong with the compressToJpeg() method, at least on my device I don't know.

Here is the final code for my doInBackground method:

protected Void doInBackground(Integer... params) 
{
    int lineHeight = mHeight / mBufferSize;
    int currentHeight = 0;

    Bitmap result = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(result);

    Log.d("output", "saving photo: "+mWidth+", "+mHeight);
    File outputPath = new File(Environment.getExternalStorageDirectory().getPath() + "/camerafluid-output");
    outputPath.mkdirs();
    for (int i = 0; i < mBufferSize; i++)
    {
        File imageFile = new File(mCachePath, "image-"+i);
        File outputFile = new File(outputPath, "image-"+i+".jpg");

        if (!imageFile.exists())
        {
            Log.d("output", "image "+i+" not found on cache directory");
            continue;
        }

        try
        {
            int size = (int)imageFile.length();
            byte[] imageBytes = new byte[size];
            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(imageFile));
            buf.read(imageBytes, 0, size);
            buf.close();

            int[] imagePixels = MainActivity.convertYUV420_NV21toRGB8888(imageBytes, mWidth, mHeight);
            imageBytes = null;
            Bitmap bitmapImage = Bitmap.createBitmap(imagePixels, mWidth, mHeight, Bitmap.Config.ARGB_8888);
            imagePixels = null;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            if (!bitmapImage.compress(CompressFormat.JPEG, 50, out))
            {
                Log.d("output", "problem converting yuv to jpg");
                break;
            }

            FileOutputStream s = new FileOutputStream(outputFile);
            s.write(out.toByteArray());
            s.flush();
            s.close();
            s = null;

            currentHeight += lineHeight;
            Log.d("output", "currentHeight: "+currentHeight);

            publishProgress((int)((i / (float)mBufferSize) * 100));
            System.gc();
        }
        catch(Exception e)
        {

        }

        if (isCancelled())
        {
            break;
        }

    }

    return null;
}

The method is converting the Yuv data to RGB and creating a bitmap so I can compress to JPEG and save to the external storage. This was only for testing purposes, and this way, there is no Signal error 11 or an OutOfMemory exception. I already tried with a buffer of 40 images.

The YUV -> RGB converter was found here Displaying YUV Image in Android. And I'm using minhaz idea to cache the buffer on disk before processing the images to avoid high memory usage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!