7

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;
}
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
Oritm
  • 2,113
  • 2
  • 25
  • 40

3 Answers3

17

Use the method Bitmap.createScaledBitmap() :)

Jave
  • 31,598
  • 14
  • 77
  • 90
0

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

DNRN
  • 2,397
  • 4
  • 30
  • 48
0

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.

Sparky
  • 8,437
  • 1
  • 29
  • 41