2014-02-13 38 views
0

我正在尝试重新调整图像的大小并保持其宽高比位图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); 

我发现通过街道波士顿提供了这个答案,并试图在我的应用程序使用它,但我可能会搞砸的变量和我得到一个空白图像大小相同,原来,任何人都可以表演我如何正确实现这一点?

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

阿里你好,非常感谢你的代码片断这解决了我的问题。 – joebohen

回答

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