简体   繁体   中英

How to resize an actual size of image in android?

My app goes to the gallery and the user picks an image then return to onActivityResult method in my activity where i got file path of the image. I can get the bitmap's height and width by implementing:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
int height = options.outHeight;
int width = options.outWidth;

Now, If the bitmap has width greater than 500 px, I need to resize the image to have a max width of 500 px, and the scale down the height. This is the formula that I will use for scaling the height down:

        int origWidth = width;
        int origHeight = height;
        int destHeight, destWidth;

        if (origWidth <= 500 || origHeight <= 500) {
            destWidth = origWidth;
            destHeight = origHeight;
        } else {
            destWidth = 500;
            destHeight = (origHeight * destWidth) / origWidth;
        }

        Bitmap bitmap = BitmapFactory.create(/*bitmap source*/, 0, 0, destWidth, destHeight); 

How can I create a bitmap, because the inJustDecodeBounds property is set to true, returning null for the bitmap object. And if I set it to false, picking image larger than the memory can hold will cause for OutOfMemory error.

uses Intent("com.android.camera.action.CROP")

This is a sample code:

Intent intent = new Intent("com.android.camera.action.CROP");
// this will open all images in the Galery
intent.setDataAndType(photoUri, "image/*");
intent.putExtra("crop", "true");
// this defines the aspect ration
intent.putExtra("aspectX", aspectY);
intent.putExtra("aspectY", aspectX);
// this defines the output bitmap size
intent.putExtra("outputX", sizeX);
intent.putExtra("outputY", xizeY);
// true to return a Bitmap, false to directly save the cropped iamge
intent.putExtra("return-data", false);
//save output image in uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

Try the following snippet to scale down an image if its width > 500.

public static Bitmap createScaledBitmap(Bitmap bitmap, int reqWidth) {
    if (bitmap.getWidth() > reqWidth) {
        int height = reqWidth / bitmap.getWidth() * bitmap.getHeight();

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, height, true);
        bitmap.recycle();
        return scaledBitmap;
    }
    return bitmap;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM