Android rotate bitmap 90 degrees results in squash

2019-03-18 03:33发布

I am trying to rotate a bitmap image 90 degrees to change it from a landscape format to a portrait format. Example:

[a, b, c, d]
[e, f, g, h]
[i, j, k, l]

rotated 90 degree clockwise becomes

[i,e,a]
[j,f,b]
[k,g,c]
[l,h,d]

Using the code below (from an online example) the image is rotated 90 degrees but retains the landscape aspect ratio so you end up with a vertically squashed image. Am I doing something wrong? Is there another method I need to use? I am also willing to rotate the jpeg file that I'm using to create the bitmap if that is easier.

 // create a matrix for the manipulation
 Matrix matrix = new Matrix();
 // resize the bit map
 matrix.postScale(scaleWidth, scaleHeight);
 // rotate the Bitmap
 matrix.postRotate(90);

 // recreate the new Bitmap
 Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOriginal, 0, 0, widthOriginal, heightOriginal, matrix, true); 

4条回答
冷血范
2楼-- · 2019-03-18 03:45

check the canvas size where you draw the bitmap, maybe your canvas is still landscape, so only the square part of the rotated bitmap could be seen.

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-18 03:46

This is all you need to rotate the image:

Matrix matrix = new Matrix();
matrix.postRotate(90);
rotated = Bitmap.createBitmap(original, 0, 0, 
                              original.getWidth(), original.getHeight(), 
                              matrix, true);

In your code sample, you included a call to postScale. Could that be the reason your image is being stretched? Perhaps take that one out and do some more testing.

查看更多
贪生不怕死
4楼-- · 2019-03-18 03:51

This code worked great for me:

                Matrix matrix = new Matrix();

            matrix.setRotate(90, 0, 0);
            matrix.postTranslate(original.getHeight(), 0);

            rotatedBitmap = Bitmap.createBitmap(newWidth, newHeight, original.getConfig());
            Canvas tmpCanvas = new Canvas(rotatedBitmap);
            tmpCanvas.drawBitmap(original, matrix, null);
            tmpCanvas.setBitmap(null);
查看更多
Bombasti
5楼-- · 2019-03-18 04:04

Here's how you would rotate it properly (this insures proper rotation of the image)

public static Bitmap rotate(Bitmap b, int degrees) {
    if (degrees != 0 && b != null) {
        Matrix m = new Matrix();

        m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
        try {
            Bitmap b2 = Bitmap.createBitmap(
                    b, 0, 0, b.getWidth(), b.getHeight(), m, true);
            if (b != b2) {
                b.recycle();
                b = b2;
            }
        } catch (OutOfMemoryError ex) {
           throw ex;
        }
    }
    return b;
}
查看更多
登录 后发表回答