I am trying to compress a bitmap that is picked from gallery or captured by camera before sending to server. Now I do it following these steps:
1) get the path of the image.
2) get bitmap from this path.
3) check initial width and height of bitmap, and compare them to the max width and height and then use a ratio factor to adjust width and height.
4) check and rotate bitmap correctly using exif.
5) finaly lower the quality to get a final compressed bitmap.
The code:
private static final float max_width = 1280.0f;
private static final float max_height = 1280.0f;
private static final float max_ratio = max_width/max_height;
private void CompressImage(String path , Bitmap bitmap_original){
//get width and height of original bitmap
int original_width = bitmap_original.getWidth();
int original_height = bitmap_origianl.getHeight();
float original_ratio = (float)width/(float)height;
if(original_height > max_height || original_width > max_width){
//adjust bitmap dimensions
int width = 0;
int height = 0;
if(original_ratio<max_ratio){
width= (int)((max_height/original_height)*original_width);
height=(int) max_height;
}else if(original_ratio>max_ratio){
height= (int)((max_width/original_width)*original_height);
width= (int)max_width;
}else{
height = max_height;
width = max_width;
}
//adjust the bitmap
Bitmap adjusted_bitmap = Bitmap.createScaledBitmap(bitmap_original,width,height,false);
//check rotation
Matrix matrix = new Matrix();
try{
ExifInterface exif = new ExifInterface(path);
int original_orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION , ExifInterface.ORIENTATION_UNDEFINED);
if(original_orientation == ExifInterface.ORIENTATION_ROTATE_90){
matrix.setRotate(90);
}else if(original_orientation == ExifInterface.ORIENTATION_180){
matrix.setRotate(180);
}else if(original_orientation == ExifInterface.ORIENTATION_270){
matrix.setRotate(270);
}
Bitmap rotated_adjusted_bitmap = Bitmap.createBitmap(adjusted_bitmap , 0 , 0 , adjusted_bitmap.getWidth(), adjusted_bitmap.getHeight(),matrix,true);
//lower the quality
ByteArrayOutputStream out = new ByteArrayOutputStream();
adjusted_rotated_bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
Bitmap adjusted_rotated_lowquality_bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
}catch(IOException e){
}
}else{
//keep bitmap as is
Bitmap adjusted_bitmap = bitmap_original;
}
}
The problem
Everything above works fine, but the problem is that in some cases the app will crash with an Out Of Memory exception.
Is there something wrong with my code?
I don't know a lot concerning bitmaps and compression.
Thanks for your help.