0

I am attempting to re-size an image and maintain its aspect ratio the bitmap mBitmap measures 1200x539 and I need to reduce this to about 1/3rd of that.

 mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;

                int H = (int)mBitmap.getHeight();      
                int W =(int)mBitmap.getWidth();            
                nBitmap = BitmapScaler.setBitmapScale(mBitmap, W,H);

I spotted this answer provided by Streets Of Boston and have attempted to use it in my app but I may have messed up the variables and I am getting a blank image the same size as the original, can anyone show me how to achieve this correctly?

Scaled Bitmap maintaining aspect ratio

The code runs without error but returns an image the same size as the original!

public static Bitmap setBitmapScale(Bitmap originalImage, int width, int height){

            Bitmap background = Bitmap.createBitmap((int)width, (int)height, Config.ARGB_8888);
            float originalWidth = originalImage.getWidth(), originalHeight = originalImage.getHeight();
            Canvas canvas = new Canvas(background);
            float scale = width/originalWidth;
            float xTranslation = 0.0f, yTranslation = (height - originalHeight * scale)/2.0f;
            Matrix transformation = new Matrix();
            transformation.postTranslate(xTranslation, yTranslation);
            transformation.preScale(scale, scale);
            Paint paint = new Paint();
            paint.setFilterBitmap(true);
            canvas.drawBitmap(originalImage, transformation, paint);
            return background;
      }
Community
  • 1
  • 1
joebohen
  • 145
  • 1
  • 14

1 Answers1

0

Below are two functions I am using for my own purpose, this might help you

/************************ Calculations for Image Sizing *********************************/ 
public Drawable ResizeImage (int imageID) { 

int newWidth = 1000; //This is new width which can be (1/3) * orignalWidth

double ratio = deviceWidth / imageWidth; 
int newImageHeight = (int) (imageHeight * ratio); 

Bitmap bMap = BitmapFactory.decodeResource(getResources(), imageID); 
Drawable drawable = new BitmapDrawable(this.getResources(),getResizedBitmap(bMap,newImageHeight,(int) deviceWidth)); 

return drawable; 
}

/************************ Resize Bitmap *********************************/ 
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { 

int width = bm.getWidth(); 
int height = bm.getHeight(); 

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

// create a matrix for the manipulation 
Matrix matrix = new Matrix(); 

// resize the bit map 
matrix.postScale(scaleWidth, scaleHeight); 

// recreate the new Bitmap 
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); 

return resizedBitmap; 
}
Androider
  • 2,884
  • 5
  • 28
  • 47