2012-04-26 85 views
6

我正在保存處於橫向模式的相機的圖像。所以它被保存在橫向模式下,然後我在它上應用一個覆蓋層,這也是在橫向模式下。我想旋轉那個圖像然後保存。例如如果我有這個在Android中旋轉保存的位圖

enter image description here

我想90度一次向順時針方向旋轉,使之本,並將其保存到SD卡:

enter image description here

這是怎麼回事實現呢?

回答

12
void rotate(float x) 
    { 
     Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.tedd); 

     int width = bitmapOrg.getWidth(); 

     int height = bitmapOrg.getHeight(); 


     int newWidth = 200; 

     int newHeight = 200; 

     // calculate the scale - in this case = 0.4f 

     float scaleWidth = ((float) newWidth)/width; 

     float scaleHeight = ((float) newHeight)/height; 

     Matrix matrix = new Matrix(); 

     matrix.postScale(scaleWidth, scaleHeight); 
     matrix.postRotate(x); 

     Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,width, height, matrix, true); 

     iv.setScaleType(ScaleType.CENTER); 
     iv.setImageBitmap(resizedBitmap); 
    } 
+0

修改這個功能,圖像旋轉,然後將它保存... – MAC 2012-04-26 11:58:55

+0

你做了什麼? – MAC 2012-04-26 13:13:40

+0

是的,它的確如此。非常感謝。 – prometheuspk 2012-04-27 08:20:53

0

使用Matrix.rotate(度數)並使用該旋轉矩陣將位圖繪製到它自己的畫布上。我不知道,如果你可能需要在繪製之前製作位圖的副本。

使用Bitmap.compress(...)將您的位圖壓縮到輸出流。

1

您可以使用Canvas API來做到這一點。請注意,您需要切換寬度和高度。

final int width = landscapeBitmap.getWidth(); 
    final int height = landscapeBitmap.getHeight(); 
    Bitmap portraitBitmap = Bitmap.createBitmap(height, width, Bitmap.Config.ARGB_8888); 
    Canvas c = new Canvas(portraitBitmap); 
    c.rotate(90, height/2, width/2); 
    c.drawBitmap(landscapeBitmap, 0,0,null); 
    portraitBitmap.compress(CompressFormat.JPEG, 100, stream); 
2

入住這

public static Bitmap rotateImage(Bitmap src, float degree) 
{ 
     // create new matrix 
     Matrix matrix = new Matrix(); 
     // setup rotation degree 
     matrix.postRotate(degree); 
     Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true); 
     return bmp; 
} 
0

Singhak的解決方案正常工作。 如果你需要適應的結果位圖(也許ImageView的),你可以擴展方法如下規模:

public static Bitmap rotateBitmapZoom(Bitmap bmOrg, float degree, float zoom){ 
    Matrix matrix = new Matrix(); 
    matrix.postRotate(degree); 

    float newHeight = bmOrg.getHeight() * zoom; 
    float newWidth = bmOrg.getWidth()/100 * (100.0f/bmOrg.getHeight() * newHeight); 

    return Bitmap.createBitmap(bmOrg, 0, 0, (int)newWidth, (int)newHeight, matrix, true); 
}