Aparna
Aparna

Reputation: 119

Android OutOfMemory converting image byte array into Drawable

I am developing chatting application which connects with Facebook and Gatlk, fetch contacts and VCard using ASMACK API and showing them in ListView.

Getting contact images from VCard which is in BYTE ARRAY. I need to convert this byte array into image(Bitmap or Drawable), but getting OutOfMemory exception while creating Drawable from image byte array and also while scrolling ListView it occurs.

Below is the code snippet, also tried by converting it into Bitmap, but with Bitmap outofmemory exception is coming more frequently. Tried with bitmap.recyle() method as solution provided at forum for such issue. But using recycle() most of places getting exception something like “using recycled images”.

Here if the LOG:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
 E/dalvikvm-heap(26048): 10000-byte external allocation too large for this process.
 E/GraphicsJNI(26048): VM won't let us allocate 10000 bytes

Please let me know the best approach to convert bytearray in Bitmap or Drawable. Code snippet is here:

public static Drawable createDrawableImageFromByteArray(Context context, byte[] imageByteArray){
    Drawable drawable = null;
    try{
        if(imageByteArray != null){                                                                                                 
            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = true;                                                            
            int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)55);
            int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)55);

            if (heightRatio > 1 || widthRatio > 1){
                if (heightRatio > widthRatio){
                    bmpFactoryOptions.inSampleSize = heightRatio;  
                } else {
                    bmpFactoryOptions.inSampleSize = widthRatio;   
                }   
            }                                              
            bmpFactoryOptions.inJustDecodeBounds = false;
            bmpFactoryOptions.inPurgeable = true;
            bmpFactoryOptions.inInputShareable = true;
            drawable = Drawable.createFromResourceStream(context.getResources(), new TypedValue(), new ByteArrayInputStream(imageByteArray), "testimg", bmpFactoryOptions);
        }
    }catch(OutOfMemoryError e){
        Utils.debugLog("****** createBitmaException :: " + e);
    }catch(Exception e){
        Utils.debugLog("****** createBitmaException :: " + e);
    }
    return drawable;                             
}

Thank you

Upvotes: 0

Views: 1971

Answers (1)

Kuffs
Kuffs

Reputation: 35661

See the documentation here. It should help you.

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

Upvotes: 0

Related Questions