Android Image Image

I tried this for some time, I would like to create wallpaper from Bitmap . Say the desired wallpaper size is 320x480, and the size of the original image is 2048x2048.

I'm not sure if the term β€œfit to fit” is appropriate, but what I would like to achieve is to get most of the image that is equally related to the size of the wallpaper (320x480).

So, in this case, I would like to get 2048x1365 or (1365.333 ... to be precise) from the Bitmap source and scale it to 320x480.

The method I tried:

1) Crop the bitmap first to 2048x1365

 bm = Bitmap.createBitmap(bm, xOffset, yOffset, 2048, 1365); 

2) Zoom to 320x480

 bm = Bitmap.createScaledBitmap(bm, 320, 480, false); 

which caused the OutOfMemory error.

Is there any way to achieve this?

Hi,

dezull

+5
source share
3 answers

Thanks to the open source code, I found the answer from the Android Gallery source code here on line 230: -D

 croppedImage = Bitmap.createBitmap(mOutputX, mOutputY, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(croppedImage); Rect srcRect = mCrop.getCropRect(); Rect dstRect = new Rect(0, 0, mOutputX, mOutputY); int dx = (srcRect.width() - dstRect.width()) / 2; int dy = (srcRect.height() - dstRect.height()) / 2; // If the srcRect is too big, use the center part of it. srcRect.inset(Math.max(0, dx), Math.max(0, dy)); // If the dstRect is too big, use the center part of it. dstRect.inset(Math.max(0, -dx), Math.max(0, -dy)); // Draw the cropped bitmap in the center canvas.drawBitmap(mBitmap, srcRect, dstRect, null); 
+15
source

I know this is an incredibly late answer, but something like this is possible:

 public static Bitmap scaleCropToFit(Bitmap original, int targetWidth, int targetHeight){ //Need to scale the image, keeping the aspect ration first int width = original.getWidth(); int height = original.getHeight(); float widthScale = (float) targetWidth / (float) width; float heightScale = (float) targetHeight / (float) height; float scaledWidth; float scaledHeight; int startY = 0; int startX = 0; if (widthScale > heightScale) { scaledWidth = targetWidth; scaledHeight = height * widthScale; //crop height by... startY = (int) ((scaledHeight - targetHeight) / 2); } else { scaledHeight = targetHeight; scaledWidth = width * heightScale; //crop width by.. startX = (int) ((scaledWidth - targetWidth) / 2); } Bitmap scaledBitmap = Bitmap.createScaledBitmap(original, (int) scaledWidth, (int) scaledHeight, true); Bitmap resizedBitmap = Bitmap.createBitmap(scaledBitmap, startX, startY, targetWidth, targetHeight); return resizedBitmap; } 
+9
source

here is the answer that gives you most of the way: How to crop image in android?

0
source

All Articles