2013-01-17 35 views
0

当我在应用程序中调整一个图像位图的大小时,出现问题,图像质量下降。调整大小时Android的质量不佳位图

我调整大小的代码如下..

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { 
    Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, 
      Config.ARGB_8888); 

    float ratioX = newWidth/(float) bm.getWidth(); 
    float ratioY = newHeight/(float) bm.getHeight(); 
    float middleX = newWidth/2.0f; 
    float middleY = newHeight/2.0f; 

    Matrix scaleMatrix = new Matrix(); 
    scaleMatrix.postScale(ratioX, ratioY, middleX, middleY); 

    Paint paint = new Paint(); 
    paint.setAntiAlias(true); 
    paint.setFilterBitmap(true); 
    paint.setDither(true); 

    Canvas canvas = new Canvas(scaledBitmap); 
    canvas.setMatrix(scaleMatrix); 
    canvas.drawBitmap(bm, middleX - bm.getWidth()/2, 
      middleY - bm.getHeight()/2, paint); 
    return scaledBitmap; 
} 

调整大小的位图¿什么好的解决办法?

+0

参考这个网址http://android.okhelp.cz/resize-a-bitmap-image-android-example/和HTTP:// thinkandroid.wordpress.com/2009/12/25/resizing-a-bitmap/ –

+1

为什么你不只是使用'Bitmap.createScaledBitmap(bm,newWidth,newHeight,true)'? –

回答

0

使用此代码,我希望它会帮助你

/*** 
* This method is for aspect ratio means the image is set acc. to the aspect 
* ratio. 
* 
* @param bmp 
*   bitmap passed 
* @param newWidth 
*   width you want to set for your image 
* @param newHeight 
*   hight you want to set for your image 
* @return bitmap 
*/ 
public Bitmap resizeBitmap(Bitmap bmp, int newWidth, int newHeight) { 
    Log.i(TAG, 
      "height = " + bmp.getHeight() + "\nwidth = " + bmp.getWidth()); 
    if (bmp.getHeight() > newHeight || bmp.getWidth() > newWidth) { 
     int originalWidth = bmp.getWidth(); 
     int originalHeight = bmp.getHeight(); 
     Log.i("TAG", "originalWidth = " + originalWidth 
       + "\noriginalHeight = " + originalHeight); 
     float inSampleSize; 
     if (originalWidth > originalHeight) { 
      inSampleSize = (float) newWidth/originalWidth; 
     } else { 
      inSampleSize = (float) newHeight/originalHeight; 
     } 
     newWidth = Math.round(originalWidth * inSampleSize); 
     newHeight = Math.round(originalHeight * inSampleSize); 
     Log.i("", "newWidth = " + newWidth + "\nnewHeight = " + newHeight); 
     bitmap = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); 
    } else { 
     bitmap = bmp; 
     Log.i("", "bitmapWidth = " + bitmap.getWidth() 
       + "\nbitmapHeight = " + bitmap.getHeight()); 
    } 
    return bitmap; 
} 
+0

我尝试这个解决方案,但图像质量不好...我认为,这个问题是因为我将位图转换为ByteArrayOutPutStream粘贴在PDF文档中,就像这样:Bitmap bit1 = resizeBitmap(mBitmap,100,300); \t \t \t ByteArrayOutputStream streamDoc1 = new ByteArrayOutputStream(); \t \t \t bit1.compress(Bitmap.CompressFormat.PNG,100,streamDoc1); \t \t \t byte [] docByte1 = streamDoc1.toByteArray(); \t \t \t Image image = Image.getInstance(docByte1); –