How to relase bitmap from a return method correctly?

2k Views Asked by At

Will this method will recycle the bitmap in imageUtils.mediaImageToBitmap(image, activity);?.

because I can't put recycle after the return methodBitmap;

Bitmap bitmap = imageUtils.mediaImageToBitmap(image, activity);
//some process
...
//some process
bitmap.recycle();

Update

After I'm done I put bitmap.recycle() but in imageUtils.mediaImageToBitmap(image, activity); there's a bitmap inside that function, does it require to be recycle as well?

or

bitmap.recycle() will automatically recycle the bitmap inside imageUtils.mediaImageToBitmap(image, activity);?

    public Bitmap mediaImageToBitmap(Image image, Context context) {
        Bitmap bitmap;
        //Do I need to do bitmap recycle in this method's Java Class?
        //or 
        //The other class that call this method 
        //Bitmap bitmap = imageUtils.mediaImageToBitmap(image, activity);
        //Then bitmap.recycle is enough?
        return bitmap;
    }
2

There are 2 best solutions below

1
ahsanali274 On BEST ANSWER

Your imageUtils.mediaImageToBitmap(image, activity); should only be returning reference to bitmap object which you assign to your local variable. In other words there is only one bitmap object and calling bitmap.recycle() once will automatically recycle that bitmap object.

2
Mitesh Machhoya On

Your statement will not be executed after the return statement, but there is one block that block will execute after the return statement that is finally block with try catch if you know that concept:

public Bitmap methodBitmap() 
{
        Bitmap bitmap
        try {
            bitmap = imageUtils.mediaImageToBitmap(image, activity);
            //some process
        ...
            //some process

            return bitmap;
        }
        catch (Exception e) {
            // Do necessary step on exception case
            return bitmap;
        }
        finally {
            bitmap.recycle();    
        }
}

Note : Take necessary argument on methodBitmap as per your need