Android bitmap scale banner image to portrait - android

I'm pulling in images from a cms and they are banner style (width = 900, height = 250). I have to use them in a fullscreen portrait mode, so naturally they are badly distorted. I've tried a lot of different things with xml, resizing bitmaps, picasso transforms etc..but not sure what else to try at this point. The only time I've been able to maintain quality is by centercropping, but that isn't an option. I need the image to maintain its aspect ratio. Is this even possible to do without sacrificing the aspect ratio? The images aspect ratio 1.7 while the desired is 0.5625 on my galaxy s5.
Edit for more details:
This is a proprietary project so I can't include the images I'm using but they are banner style. They are being used in an imageview that is screenSizeHeight - toolbarHeight and screensizewidth / 1.2.
this is how I'm trying to resize the bitmap. It's just centercropping though and is much too large.
public static final Bitmap scaleAndCropBitmapByPixelDimensions(final Context context, final Bitmap sourceBitmap, final int targetWidth, final int targetHeight)
{
try
{
if (context != null && sourceBitmap != null)
{
int srcWidth = sourceBitmap.getWidth();
int srcHeight = sourceBitmap.getHeight();
float targetAspectRatio = (float)targetWidth / (float)targetHeight;
float srcAspectRatio = (float)srcWidth / (float)srcHeight;
int scaleWidth = targetWidth;
int scaleHeight = targetHeight;
int x = 0;
int y = 0;
if (srcAspectRatio < targetAspectRatio)
{
scaleWidth = targetWidth;
scaleHeight = (int)((float)(1 / srcAspectRatio) * (float)scaleWidth);
x = 0;
y = (scaleHeight - targetHeight) / 2;
}
else
{
scaleHeight = targetHeight;
scaleWidth = (int)((float)srcAspectRatio * (float)scaleHeight);
x = (scaleWidth - targetWidth) / 2;
y = 0;
}
Bitmap scaledBitmap = Bitmap.createScaledBitmap(sourceBitmap, scaleWidth, scaleHeight, true);
Bitmap croppedBitmap = Bitmap.createBitmap(scaledBitmap, x, y, targetWidth, targetHeight);
return croppedBitmap;
}
}
catch (Exception ex)
{
//Log.e(LOG_TAG, "Error scaling and cropping bitmap", ex);
ex.printStackTrace();
}
return null;
}
Setting up the bitmap transform
#Override
public Bitmap transform(Bitmap sourceBitmap) {
i_bitmap = Utils.scaleAndCropBitmapByPixelDimensions(mContext,sourceBitmap,targetWidth,targetHeight);
if (sourceBitmap != i_bitmap) {
// Same bitmap is returned if sizes are the same
sourceBitmap.recycle();
}
return i_bitmap;
}
imageview xml
<ImageView
android:id="#+id/bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="center" />
and loading the image with picasso
Picasso.with(mContext)
.load(url)
.transform(transformation)
.into(getBg());

Well, since the desired aspect ratio is the opposite of the actual ratio, one thing you can is to simply rotate the banner images (-90º or +90º).
Of course, this is a very naive suggestion. Maybe if you give more details about the contents to be displayed or any other constraints, we'll be able to provide a better solution.

Related

How to compress multiple images size to particular(100kb) size in android?

I am new to android. I want to reduce the size of a bitmap to 100kb exactly. I get an image from the sdcard, compress it and save it to the sdcard again with a different name into a different directory. Compression works fine (3 mb like image is compressed to around 100 kb). I trying to compress 1mb image to 100kb, but i am getting size of that image is 20kb. But i need that 1mb(or 2mb (or) 3mb (or) 4mb (or) 5mb.....) image also get resize to 100kb. and my code is,,
private Bitmap getResizedBitmap(Bitmap bm, int maxSize)
{
int width = bm.getWidth();
int height = bm.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 0) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(bm, width, height, true);
}
public static Bitmap getResizedBitmap(Bitmap bm, float newHeight, float newWidth) {
float width = bm.getWidth();
float height = bm.getHeight();
float scaleWidth = (newWidth) / width;
float scaleHeight = (newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
return Bitmap.createBitmap(bm, 0, 0, (int) width, (int) height, matrix, false);
}
Using matrix
Resizing bitmap by pixel resolution is possible but resizing by its disk size is not as far as I know

Scaling bitmaps for each resolution

Is there any method that gets the phones resolution (or dp) and scales bitmaps accordingly? I have all my images in xhdpi folder and at the moment they do not scale the way they should.
I want an efficiant and memory-friendly method that can do the scaling automatically. If not, what is the next best thing? completely new area for me. So any tutorial-link is also appriciated.
this is what I use to load bitmaps atm:
public Bitmap loadBitmap(int resourceID) {
Options options = new BitmapFactory.Options();
options.inScaled = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap tempBmp = null;
try {
tempBmp = BitmapFactory.decodeResource(getResources(), resourceID,
options);
} catch (OutOfMemoryError e) {
} catch (Error e) {
}
return tempBmp;
}
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;
}

center Crop Image In proper size to set on ImageView

I am using camera API to take picture i have to open camera in different sizes according to my Image view size. I am following the sample project which we get inside Android sdk/sample/adroid-18 at the name "ApiDemo" the thing i have changed is not set camera on setcontentview. I have set the camera on Frame Layout. at first my camera preview was starched so i got the camera OptimalPreviewSize and make FrameLayout parameter width and height as wrap-content.Now the camera preview is smaller then ImageView (The size i want). If i make the size of FrameLayout parameter as match-parent then camera View is stretch.How to resolve this issue.
find this link for more specification. Android camera preview look strange
UPDATE
My camera preview size is fine now i use the on Layout method the idea was i have the bigger layout then my ImageView and now camera preview is looking good.
Now the Problem I am facing is set the image of proper size for this I have to center crop and scale in same size in like my ImageView.this Image i get by TakePicture method and saved in sdcard.
For this I am using this method:-
public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left+50, top, left + scaledWidth, top + scaledHeight+50);
// RectF targetRect = new RectF(0, 0, newWidth, newHeight/2);
// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}
But the result image quality is not good.Height Corners are cutting from top and bottom, and result image quality is not good.Pixels are stretching.
Don't tell me to use scaleType=Center_crop i can't use it in my case,and don't want to show cropping frame to user,this all process should not show on UI.
UPDATE
I used blow method for crop image from center and scale according to my imageView size
Bitmap dstBmp = ThumbnailUtils.extractThumbnail(source, newWidth, newHeight);
But the bitmap i got is not looking same the camera preview shown on FrameLayout. because camera preview is big.I think these code cropped the large area.
I tried to reduce the width and change the height but not getting the same cropped image in which ratio i want.
One more idea i have after picture crop a last image frame set automatically on FrameLayout. can we get that set frame from Frame Layout. How is this possible?
Here is question like this How to retrieve the visible part of a SurfaceView in Android do any one have solution.
I want to achieve this by this line ThumbnailUtils.extractThumbnail(source, newWidth, newHeight);and by this line i am getting src like image described in diagram .
What to change in this line exactly ????
Center crop an image may be help you this.
public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}
#Akanksha Please use this below code, you just need to pass the path of the saved image, and the hight and width of our imageview. This code works perfectly for me.
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ImageHandler {
/**
* Decode and sample down a bitmap from a file to the requested width and
* height.
*
* #param filename
* The full path of the file to decode
* #param reqWidth
* The requested width of the resulting bitmap
* #param reqHeight
* The requested height of the resulting bitmap
* #return A bitmap sampled down from the original with the same aspect
* ratio and dimensions that are equal to or greater than the
* requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
// This offers some additional logic in case the image has a
// strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might
// still
// end up being too large to fit comfortably in memory, so we
// should
// be more aggressive with sample down the image (=larger
// inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further.
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
}
I call this method inside async task because it may take too much UImemory and time
Here is how I call it.
class Asyncing extends AsyncTask {
private int reqWidth;
private int reqHeight;
private ImageView iv;
private String fileName;
private ProgressDialog pd;
public Asyncing(int reqWidth, int reqHeight, ImageView iv,
String fileName) {
super();
this.reqWidth = reqWidth;
this.reqHeight = reqHeight;
this.fileName = fileName;
this.iv = iv;
}
#Override
protected Bitmap doInBackground(String... params) {
return ImageHandler.decodeSampledBitmapFromFile(params[0],
reqWidth, reqHeight);
}
#Override
protected void onPostExecute(Bitmap result) {
iv.setImageBitmap(result);
if (pd.isShowing()) {
pd.setMessage(getString(R.string.completed));
pd.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CustomerDetailsActivity.this, "",
getString(R.string.processing_signature));
super.onPreExecute();
}
}
This is how you need to call the asynctask
signedImagePath = data.getExtras().getString("imagePath");
new Asyncing(signature_img.getWidth(), signature_img.getHeight(),
signature_img, "spenTest.png").execute(signedImagePath);
above code is written according to my requirements,you modify it according to yours.

Resizing a bitmap to a fixed value but without changing the aspect ratio

I'm looking for a solution for the following problem: how to change the size of a Bitmapto a fixed size (for example 512x128). The aspect ratio of the bitmap content must be preserved.
I think it should be something like this:
create an empty 512x128 bitmap
scale the original bitmap down to fit the 512x128 pixels with keeping the aspect ratio
copy the scaled into the empty bitmap (centered)
What is the simplest way to achieve this?
The reason for all this is, that the GridView messes the layout up when the aspect ratio of an image differs from the other. Here is a screenshot (all images except the last one have the aspect ratio of 4:1):
screenshot
Try this, calculate the ratio and then rescale.
private Bitmap scaleBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
Log.v("Pictures", "Width and height are " + width + "--" + height);
if (width > height) {
// landscape
float ratio = (float) width / maxWidth;
width = maxWidth;
height = (int)(height / ratio);
} else if (height > width) {
// portrait
float ratio = (float) height / maxHeight;
height = maxHeight;
width = (int)(width / ratio);
} else {
// square
height = maxHeight;
width = maxWidth;
}
Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);
bm = Bitmap.createScaledBitmap(bm, width, height, true);
return bm;
}
The answer by Coen Damen doesn't always respect Max Height and Max Width.
Here's an answer that does:
private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > 1) {
finalWidth = (int) ((float)maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float)maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
return image;
} else {
return image;
}
}
I have stumbled upon the same problem a number of times in my projects and each time due to lack of time (and laziness) I would be satisfied with a less than optimum solution. But recently I found some time to crack down this particular issue. Here is my solution and I hope it helps someone down the line.
Bitmap scaleDownLargeImageWithAspectRatio(Bitmap image)
{
int imageVerticalAspectRatio,imageHorizontalAspectRatio;
float bestFitScalingFactor=0;
float percesionValue=(float) 0.2;
//getAspect Ratio of Image
int imageHeight=(int) (Math.ceil((double) image.getHeight()/100)*100);
int imageWidth=(int) (Math.ceil((double) image.getWidth()/100)*100);
int GCD=BigInteger.valueOf(imageHeight).gcd(BigInteger.valueOf(imageWidth)).intValue();
imageVerticalAspectRatio=imageHeight/GCD;
imageHorizontalAspectRatio=imageWidth/GCD;
Log.i("scaleDownLargeImageWIthAspectRatio","Image Dimensions(W:H): "+imageWidth+":"+imageHeight);
Log.i("scaleDownLargeImageWIthAspectRatio","Image AspectRatio(W:H): "+imageHorizontalAspectRatio+":"+imageVerticalAspectRatio);
//getContainer Dimensions
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
int displayHeight = getWindowManager().getDefaultDisplay().getHeight();
//I wanted to show the image to fit the entire device, as a best case. So my ccontainer dimensions were displayWidth & displayHeight. For your case, you will need to fetch container dimensions at run time or you can pass static values to these two parameters
int leftMargin = 0;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
int containerWidth = displayWidth - (leftMargin + rightMargin);
int containerHeight = displayHeight - (topMargin + bottomMargin);
Log.i("scaleDownLargeImageWIthAspectRatio","Container dimensions(W:H): "+containerWidth+":"+containerHeight);
//iterate to get bestFitScaleFactor per constraints
while((imageHorizontalAspectRatio*bestFitScalingFactor <= containerWidth) &&
(imageVerticalAspectRatio*bestFitScalingFactor<= containerHeight))
{
bestFitScalingFactor+=percesionValue;
}
//return bestFit bitmap
int bestFitHeight=(int) (imageVerticalAspectRatio*bestFitScalingFactor);
int bestFitWidth=(int) (imageHorizontalAspectRatio*bestFitScalingFactor);
Log.i("scaleDownLargeImageWIthAspectRatio","bestFitScalingFactor: "+bestFitScalingFactor);
Log.i("scaleDownLargeImageWIthAspectRatio","bestFitOutPutDimesions(W:H): "+bestFitWidth+":"+bestFitHeight);
image=Bitmap.createScaledBitmap(image, bestFitWidth,bestFitHeight, true);
//Position the bitmap centre of the container
int leftPadding=(containerWidth-image.getWidth())/2;
int topPadding=(containerHeight-image.getHeight())/2;
Bitmap backDrop=Bitmap.createBitmap(containerWidth, containerHeight, Bitmap.Config.RGB_565);
Canvas can = new Canvas(backDrop);
can.drawBitmap(image, leftPadding, topPadding, null);
return backDrop;
}
https://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap(android.graphics.Bitmap, int, int, boolean)
and make sure that both the dstWidth and dstHeight are obtained from src.getWidth()*scale and src.getHeight()*scale, where scale is a value that you need to determine to make sure the scaled bitmap fits inside 512x128.
I think #Coen's answer is not right solution for this question. I also needed a method like this but I wanted to square image.
Here is my solution for square image;
public static Bitmap resizeBitmapImageForFitSquare(Bitmap image, int maxResolution) {
if (maxResolution <= 0)
return image;
int width = image.getWidth();
int height = image.getHeight();
float ratio = (width >= height) ? (float)maxResolution/width :(float)maxResolution/height;
int finalWidth = (int) ((float)width * ratio);
int finalHeight = (int) ((float)height * ratio);
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
if (image.getWidth() == image.getHeight())
return image;
else {
//fit height and width
int left = 0;
int top = 0;
if(image.getWidth() != maxResolution)
left = (maxResolution - image.getWidth()) / 2;
if(image.getHeight() != maxResolution)
top = (maxResolution - image.getHeight()) / 2;
Bitmap bitmap = Bitmap.createBitmap(maxResolution, maxResolution, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(image, left, top, null);
canvas.save();
canvas.restore();
return bitmap;
}
}

Image background according the size of the screen without using nine patch

I have an image background like the first image of squareup image: https://market.android.com/details?id=com.squareup.cardcase&hl=fr
I need to display this image background in the screen (fill_parent) in every size of screen.
How can I do? I can't use nine patch due to geometric issue of the image. Do I need to make the image in all the size?
Thanks!
In code (rather than via the layout XML) you can create a bitmap of the right aspect ratio (device height x width) by cropping the image after scaling the bitmap to be big enough to crop. You need to make sure that the image can be scaled up/down (preferably down) without losing sharpness. You also need to be sure that important information will not be lost when the image is cropped with different aspect ratios.
Once you have the resulting bitmap then place it on the display as an ImageView's content.
I find that it is better to size logos separately from underlying images and layer image views on on top of each other so that the text remains crisp.
I created a subclass of the ImageView class to encapsulate the resizing and cropping. The only method of value is the overridden onMeasure() method:
/**
* Override the onMeasure method to resize the Bitmap as needed
*/
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Drawable currentDrawable = this.getDrawable();
BitmapDrawable theBitmapDrawable;
if (BitmapDrawable.class.isInstance(currentDrawable)){
// We have a bitmap to work with
theBitmapDrawable = (BitmapDrawable) currentDrawable;
Bitmap currentBitmap = theBitmapDrawable.getBitmap();
Bitmap resizedBitmap = null;
if (currentBitmap != null) {
int currentHeight = currentBitmap.getHeight();
int currentWidth = currentBitmap.getWidth();
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
if ((currentHeight != parentHeight) || (currentWidth != parentWidth)) {
// The bitmap needs to be resized, and/or cropped to fit
if ((currentHeight < parentHeight) || (currentWidth < parentWidth)) {
// Need to make the bitmap larger
float heightFactor = (float) parentHeight / (float) currentHeight;
float widthFactor = (float) parentWidth / (float) currentWidth;
float scaleFactor;
// Choose the largest factor
if (Float.compare(heightFactor, widthFactor) < 0) {
scaleFactor = widthFactor;
} else {
scaleFactor = heightFactor;
}
int dstWidth = (int) (currentWidth * scaleFactor);
int dstHeight = (int) (currentHeight * scaleFactor);
if (dstWidth < parentWidth) dstWidth = parentWidth; // Deal with off by one rounding errors
if (dstHeight < parentHeight) dstHeight = parentHeight; // Deal with off by one rounding errors
resizedBitmap = Bitmap.createScaledBitmap(currentBitmap, dstWidth, dstHeight, true);
currentBitmap.recycle();
} else if ((currentHeight > parentHeight) && (currentWidth > parentWidth)){
// Need to make the splash screen bitmap smaller
float heightFactor = (float) parentHeight / (float) currentHeight;
float widthFactor = (float) parentWidth / (float) currentWidth;
float scaleFactor;
// Choose the largest factor
if (Float.compare(heightFactor, widthFactor) < 0) {
scaleFactor = widthFactor;
} else {
scaleFactor = heightFactor;
}
int dstWidth = (int) (currentWidth * scaleFactor);
int dstHeight = (int) (currentHeight * scaleFactor);
if (dstWidth < parentWidth) dstWidth = parentWidth; // Deal with off by one rounding errors
if (dstHeight < parentHeight) dstHeight = parentHeight; // Deal with off by one rounding errors
resizedBitmap = Bitmap.createScaledBitmap(currentBitmap, dstWidth, dstHeight, true);
currentBitmap.recycle();
} else {
// No need to resize the image - we'll just need to crop it
resizedBitmap = currentBitmap;
}
// Now crop the image so that it fits the aspect ratio of the screen
currentHeight = resizedBitmap.getHeight();
currentWidth = resizedBitmap.getWidth();
Bitmap newBitmap;
if ((currentHeight != parentHeight) || (currentWidth != parentWidth)) {
// Crop the image to fit exactly
int startX = (currentWidth - parentWidth)/2;
if (startX < 0) startX = 0; // Hmm!
int startY = (currentHeight - parentHeight)/2;
if (startY < 0) startY = 0; // Hmm! again
newBitmap = Bitmap.createBitmap(resizedBitmap, startX, startY, parentWidth, parentHeight);
resizedBitmap.recycle();
} else {
// The resized image is the exact right size
newBitmap = resizedBitmap;
}
this.setImageBitmap(newBitmap);
}
}
}
}

Categories

Resources