Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android rotate bitmap 90 degrees results in squashed image. Need a true rotate between portrait and landscape

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); 
like image 908
user999764 Avatar asked Dec 22 '11 19:12

user999764


2 Answers

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.

like image 123
SharkAlley Avatar answered Nov 12 '22 20:11

SharkAlley


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;
}
like image 39
Tolga E Avatar answered Nov 12 '22 19:11

Tolga E