在安卓系统中旋转已保存的位图

7
我正在保存一张横向模式的相机图片。因此,它也会以横向模式保存,然后我又在其上应用了一个同样是横向模式的覆盖层。我想要旋转该图像,然后再保存。例如,如果我有这个:

enter image description here

我想要将其顺时针旋转90度并保存到SD卡中:

enter image description here

如何完成这个操作?

5个回答

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

4
小心,还要缩小新图像 :) - cV2

7

请检查这个

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

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

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

0
使用Matrix.rotate(degrees)并将Bitmap绘制到其自己的Canvas上,使用旋转矩阵。不过,在绘制之前,您可能需要复制位图。
使用Bitmap.compress(...)将位图压缩到输出流中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接