Oritm
Oritm

Reputation: 2120

Resizing a bitmap

The code below resizes a bitmap and keeps the aspect ratio. I was wondering if there is a more efficient way of resizing, because i got the idea that i'm writing code that is already available in the android API.

private Bitmap resizeImage(Bitmap bitmap, int newSize){
    int width = bitmap.getWidth();
    int height = bitmap.getHeight(); 

    int newWidth = 0;
    int newHeight = 0;

    if(width > height){
        newWidth = newSize;
        newHeight = (newSize * height)/width;
    } else if(width < height){
        newHeight = newSize;
        newWidth = (newSize * width)/height;
    } else if (width == height){
        newHeight = newSize;
        newWidth = newSize;
    }

    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);

    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, 
            width, height, matrix, true); 

    return resizedBitmap;
}

Upvotes: 7

Views: 17246

Answers (3)

Jave
Jave

Reputation: 31856

Use the method Bitmap.createScaledBitmap() :)

Upvotes: 17

Sparky
Sparky

Reputation: 8477

Depends on how you're using the image. If all you want to do is display the bitmap in a View, just call myImageView.setImageBitmap(bitmap) and let the framework resize it. But if you're concerned about memory, scaling first may be a good approach.

Upvotes: 0

DNRN
DNRN

Reputation: 2499

I really don't think so, I have done almost the same way as you, and got the idea from the android developer pages...

Upvotes: 0

Related Questions