重新调整大小图像保持宽高比

时间:2014-02-13 09:09:45

标签: android image bitmap

我正在尝试重新调整图像大小并保持其宽高比,位图mBitmap测量为1200x539,我需要将其减少到大约1/3。

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

我发现Streets Of Boston提供的这个答案,并试图在我的应用程序中使用它,但我可能搞乱了变量,我得到一个与原始大小相同的空白图像,任何人都可以告诉我如何实现这是正确的吗?

Scaled Bitmap maintaining aspect ratio

代码运行时没有错误,但返回的图像大小与原始图像相同!

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

1 个答案:

答案 0 :(得分:0)

以下是我为自己的目的使用的两个功能,这可能对您有所帮助

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