Scaled Bitmap maintaining aspect ratio
This will respect maxWidth and maxHeight, which means the resulting bitmap will never have dimensions larger then those:
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 > ratioBitmap) { finalWidth = (int) ((float)maxHeight * ratioBitmap); } else { finalHeight = (int) ((float)maxWidth / ratioBitmap); } image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true); return image; } else { return image; }}
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.
here is a method from my Utils class, that does the job:
public static Bitmap scaleBitmapAndKeepRation(Bitmap targetBmp,int reqHeightInPixels,int reqWidthInPixels) { Matrix matrix = new Matrix(); matrix .setRectToRect(new RectF(0, 0, targetBmp.getWidth(), targetBmp.getHeight()), new RectF(0, 0, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.CENTER); Bitmap scaledBitmap = Bitmap.createBitmap(targetBmp, 0, 0, targetBmp.getWidth(), targetBmp.getHeight(), matrix, true); return scaledBitmap; }