Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a scaled bitmap with createScaledBitmap in Android

Tags:

I want to create a scaled bitmap, but I seemingly get a dis-proportional image. It looks like a square while I want to be rectangular.

My code:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, 960, 960, false); 

I want the image to have a MAX of 960. How would I do that? Setting width to null doesn't compile. It's probably simple, but I can't wrap my head around it. Thanks

like image 534
EGHDK Avatar asked Jul 24 '13 16:07

EGHDK


People also ask

What is createScaledBitmap?

createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter) Creates a new bitmap, scaled from an existing bitmap, when possible.

How do I crop a bitmap in android programmatically?

height = height - topcutoff; height = height - bottomcutoff; croppedBitmap = Bitmap. createBitmap(croppedBitmap, 0, topcutoff, width, height); Basically you just set a startpoint (topcutoff) from where to begin displaying the bitmap. In your case this would be the position after 80% of your bitmap.

Can you resize a bitmap?

❓ How can I resize a BMP image? First, you need to add a BMP image file: drag & drop your BMP image file or click inside the white area to choose a file. Then adjust resize settings, and click the "Resize" button. After the process completes, you can download your result file.

How do you handle bitmaps in Android as it takes too much memory?

Choose the most appropriate decode method based on your image data source. These methods attempt to allocate memory for the constructed bitmap and therefore can easily result in an OutOfMemory exception. Each type of decode method has additional signatures that let you specify decoding options via the BitmapFactory.


1 Answers

If you already have the original bitmap in memory, you don't need to do the whole process of inJustDecodeBounds, inSampleSize, etc. You just need to figure out what ratio to use and scale accordingly.

final int maxSize = 960; int outWidth; int outHeight; int inWidth = myBitmap.getWidth(); int inHeight = myBitmap.getHeight(); if(inWidth > inHeight){     outWidth = maxSize;     outHeight = (inHeight * maxSize) / inWidth;  } else {     outHeight = maxSize;     outWidth = (inWidth * maxSize) / inHeight;  }  Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, outWidth, outHeight, false); 

If the only use for this image is a scaled version, you're better off using Tobiel's answer, to minimize memory usage.

like image 186
Geobits Avatar answered Sep 17 '22 17:09

Geobits