Monthly Archives: May 2013

Android handling images and avoiding out of memory errors

Getting the dreaded “out of memory” looms when reading large images as bitmaps. The key is to scale the image to something smaller when reading the image. There are heaps of solutions on Stack Overflow. But here is some quick code:

 


         private Bitmap mBitmap;
	
	/**
	 * Get Bitmap image from the path.
	 * Scale image to RGB_565 and rotate image 90 degrees
	 */
	private void setBitmap(String path) {
		Uri uri = Uri.fromFile(new File(path));
		ContentResolver mContentResolver = getContentResolver();
		InputStream in = null;
		try {
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inPurgeable = true;
			o.inSampleSize = 1;
			o.inPreferredConfig = Bitmap.Config.RGB_565;
			in = mContentResolver.openInputStream(uri);
			mBitmap = BitmapFactory.decodeStream(in, null, o);
			mBitmap = rotateImage(mBitmap, 90);
			in.close();
		} catch (Exception e) {
			Log.e(TAG, "file " + path + " not found");
		}
	}
        
        public Bitmap rotateImage(Bitmap src, float degree) {
		// create new matrix
		Matrix matrix = new Matrix();
		// setup rotation degree
		matrix.postRotate(degree);
		Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
		return bmp;
	}

Now if you are doing testing here is the above approach but enables you to read the file from the “assets” folder.

         private void setBitmapFromAssets(String fileName) {
		try {
			AssetManager am = this.getAssets();
			InputStream in = am.open(fileName);
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inPurgeable = true;
			o.inSampleSize = 1;
			o.inPreferredConfig = Bitmap.Config.RGB_565;
			mBitmap = BitmapFactory.decodeStream(in, null, o);
			mBitmap = rotateImage(mBitmap, 90);
			in.close();
		} catch (Exception e) {
			Log.e(TAG, "file " + fileName + " not found");
		}
	}