How to Resize a Bitmap in Android?
I have a bitmap taken of a Base64 String from my remote database, (encodedImage
is the string representing the image with Base64):
profileImage = (ImageView)findViewById(R.id.profileImage);
byte[] imageAsBytes=null;
try {
imageAsBytes = Base64.decode(encodedImage.getBytes());
} catch (IOException e) {e.printStackTrace();}
profileImage.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);
profileImage is my ImageView
Ok, but I have to resize this image before showing it on my ImageView
of my layout. I have to resize it to 120x120.
Can someone tell me the code to resize it?
The examples I found could not be applied to a base64 string obtained bitmap.
Change:
profileImage.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
To:
Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
import android.graphics.Matrix
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
EDIT: as suggested by by @aveschini, I have added bm.recycle();
in order to avoid the memory leaks. Please note that in case if you are using the previous object for some other purposes, then handle accordingly.
If you already have a bitmap, you could use the following code to resize:
Bitmap originalBitmap = <original initialization>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
originalBitmap, newWidth, newHeight, false);
Scale based on aspect ratio:
float aspectRatio = yourSelectedImage.getWidth() /
(float) yourSelectedImage.getHeight();
int width = 480;
int height = Math.round(width / aspectRatio);
yourSelectedImage = Bitmap.createScaledBitmap(
yourSelectedImage, width, height, false);
To use height as base intead of width change to:
int height = 480;
int width = Math.round(height * aspectRatio);
Scale a bitmap with a target maximum size and width, while maintaining aspect ratio:
int maxHeight = 2000;
int maxWidth = 2000;
float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);