How to scale bitmap to screen size?
Try this to Decode the Bitmap :
Where imagefilepath is the path name of image,it will be in String covert that to File by using
File photos= new File(imageFilePath);
Where photo is the File name of the Image,Now you set your height and width according t your requirements.
public void main(){
Bitmap bitmap = decodeFile(photo);
bitmap = Bitmap.createScaledBitmap(bitmap,150, 150, true);
imageView.setImageBitmap(bitmap);
}
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale++;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
How to get scaled bitmap with respect to screen size with out getting Out of memory exception
What is a good way of creating the bitmap with respect to screen with and height with minimum memory consumed ?
- Never ever create a
Bitmap
with thescreen height or width
, because that will be very huge based on thedensity
of the device.Instead use theheight
andwidth
of the screen and calculate theaspect ratio
. Now fix theheight
to a constant value (like 1200px) and then calculate thewidth
based on theaspect ratio
. TheImageView
or any other view will scale this properly. - If you really want transparency then use
Bitmap.Config.ARGB_8888
, if not could useRGB_565
or something else from the list here: http://developer.android.com/reference/android/graphics/Bitmap.Config.html - Follow below points if you are not creating a fresh
bitmap
but decoding thebitmap
from some resource:- You need to use
BitmapFactory.Options.inSampleSize
to reduce thesampling
. So how to calculate theinSampleSize
if you already know the height and width? Refer this here: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html - So you do all this, and still the
inSampleSize
is not high enough and you get theOutOfMemoryError
? Don't worry, if this is the case, you need tocatch
thisOutOfMemoryError
and in that increase yourinSampleSize
and do the bitmap decode again. Put this logic in a loop, so the crash never happens.
- You need to use
- Never ever create a
How can I destroy the bitmap after using it ?
- This is really simple. Make sure to call the
Bitmap.recycle()
method. And remove all reference to the bitmap. Once you do this, the resource will be released and GC will do the cleaning up.
- This is really simple. Make sure to call the
UPDATE: When you create the a bitmap with screen_width
and screen_height
you would end up with a huge bitmap. Instead create a less resolution bitmap that fits the whole screen. You can see the following code on how this is done.
float screenHeight = displaymetrics.heightPixels;
float screenWidth = displaymetrics.widthPixels;
float aspectRatio = screenWidth/screenHeight;
int modifiedScreenHeight = 1000;
int modifiedScreenWidth = (int) (modifiedScreenHeight * aspectRatio);
Bitmap mBitmap = Bitmap.createBitmap(modifiedScreenWidth, modifiedScreenHeight, Bitmap.Config.ARGB_8888);
Now you got the bitmap with the right aspect ratio. You could use this bitmap as it is in the ImageView
to fill the whole screen. Make sure you put android:scaleType="fitXY"
for the ImageView
.
Android: How do I scale a bitmap to fit the screen size using canvas/draw bitmap?
Rect frameToDraw = new Rect(0, 0, width, height);
RectF whereToDraw = new RectF(0, 0, width, height);
Take a look at the above code. Your are not scaling the picture. You are simply taking a part of the picture (in this case the whole picture) and pasting it somewhere (in this case the size of the original picture).
The width and heigth of the frameToDraw
rectangle should be the width and height of your picture.
Scale Bitmap maintaining aspect ratio and fitting both width and height
Based on Streets of Boston's answer, I made this method that scales and returns any Bitmap to a desired width and height, fitting both dimensions (no blank space!). It automatically adapts to more horizontal or more vertical images.
public Bitmap resizeBitmapFitXY(int width, int height, Bitmap bitmap){
Bitmap background = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
float originalWidth = bitmap.getWidth(), originalHeight = bitmap.getHeight();
Canvas canvas = new Canvas(background);
float scale, xTranslation = 0.0f, yTranslation = 0.0f;
if (originalWidth > originalHeight) {
scale = height/originalHeight;
xTranslation = (width - originalWidth * scale)/2.0f;
}
else {
scale = width / originalWidth;
yTranslation = (height - originalHeight * scale)/2.0f;
}
Matrix transformation = new Matrix();
transformation.postTranslate(xTranslation, yTranslation);
transformation.preScale(scale, scale);
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawBitmap(bitmap, transformation, paint);
return background;
}
Scaling bitmaps for each resolution
If you wanna scale bitmap for each phone resolution, you should know phone screen size, scale ratio.
This code will return width (w) & height (h) of screen.
DisplayMetrics dMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
float density = dMetrics.density;
int w = Math.round(dMetrics.widthPixels / density);
int h = Math.round(dMetrics.heightPixels / density);
activity is instance of Activity which would you like to get screen size.
You have to remember that: When your device is in landscape orientation, w > h. When it in portrait orientation w < h.
So from width & height you can detect your device is in what orientation.
Example:
From w & h of device and ratio (which you want to scale) you can calculate new bitmap size to scale it.
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
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);
return resizedBitmap;
}
Scaled Bitmap maintaining aspect ratio
What about this:
Bitmap background = Bitmap.createBitmap((int)width, (int)height, Config.ARGB_8888);
float originalWidth = originalImage.getWidth();
float originalHeight = originalImage.getHeight();
Canvas canvas = new Canvas(background);
float scale = width / originalWidth;
float xTranslation = 0.0f;
float yTranslation = (height - originalHeight * scale) / 2.0f;
Matrix transformation = new Matrix();
transformation.postTranslate(xTranslation, yTranslation);
transformation.preScale(scale, scale);
Paint paint = new Paint();
paint.setFilterBitmap(true);
canvas.drawBitmap(originalImage, transformation, paint);
return background;
I added a paint
to filter the scaled bitmap.
Related Topics
How to Solve the Install_Failed_Dexopt Error
Android M Camera Intent + Permission Bug
Removing Unused Strings During Proguard Optimisation
How to Open an Android Studio Project in Eclipse
Facebook - "Cannot Query Users by Their Username" Solution
Ics Android Enable Gps Programmatically
How Do Mpandroidchart Renderers Work and How to Write a Custom Renderer
How to Get Access Token After User Is Signed in from Gmail in Android
Android:Static Fields and Memory Leaks
Error: Status{Statuscode=Developer_Error, Resolution=Null}
Which Correct Flag of Autoconnect in Connectgatt of Ble
How to Solve Execution Failed for Task ':App:Compileflutterbuilddebug'
Android: How to Make the Keypad Always Visible
Android: How to Select Texts from Webview
How to Scale/Resize Text to Fit a Textview
Sending a Notification from a Service in Android
Firebase Chat App Setvalue Failed Error With a Public Database