Working with images in Android

I’ll try to explain some basic image functions for the Android platform. How to get images from the camera or the device I’ll explain in another post. This is more about handling image files in code.

First of all you’ll want to represent your image as a Bitmap. This way you can manipulate the pixels one by one. Use the BitmapFactory to create a Bitmap from several sources. Check the API for all the options. This example creates a bitmap from file:


File sdCard = Environment.getExternalStorageDirectory();
File imageFile = new File(sdCard, "image.jpg");
Bitmap image = BitmapFactory.decodeFile(imageFile);

A big concern when working with images is the available memory. For mobile Android devices this is very limited so watch out! You have some options to avoid the java.lang.OutOfMemoryError: bitmap size exceeds VM budget exception.

Don’t really load the image when you only need to know the size of it. You can set BitmapFactory.Options to only load image boundaries like this:


BitmapFactory.Options options = new BitmapFactory.options();
options.inJustDecodeBounds=true
BitmapFactory.decodeFile(imageFile, options);
int width = optins.outWidth;
int height = options.outHeight;

Sample the image if you only need to display


BitmapFactory.Options options = new BitmapFactory.options();
options.inJustDecodeBounds=false;
options.inSampleSize=10;
Bitmap bitmap = BitmapFactory.decodeFile(imageFile, options);

Recycle your bitmaps so garbage collector can come and get them


bitmap.recycle();
bitmap = null;

Remove callbacks when done displaying images with some Drawable object


drawable.setCallback(null);

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait