Resizing a bitmap

15,374

Use the method Bitmap.createScaledBitmap() :)

Share:
15,374
Oritm
Author by

Oritm

Making my life easier by developing: APPS iOS (Swift/Objective C) Android (Java) BACKEND SOFTWARE NodeJS (Typescript) Postgres WEBSITES Angular (Typescript) I'm also a little interested in: Python JQuery PHP

Updated on June 13, 2022

Comments

  • Oritm
    Oritm almost 2 years

    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;
    }