Rotate a saved bitmap in android

2019-01-14 05:24发布

问题:

I am saving an image from the camera that was in landscape mode. so it gets saved in landscape mode and then i apply an overlay onto it that too is in landscape mode. I want to rotate that image and then save. e.g. if i have this

I want to rotate clockwise by 90 degrees once and make it this and save it to sdcard:

How is this to be accomplished?

回答1:

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


回答2:

Check this

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


回答3:

You can use the Canvas API to do that. Note that you need to switch width and height.

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


回答4:

Use a Matrix.rotate(degrees) and draw the Bitmap to it's own Canvas using that rotating matrix. I don't know though if you might have to make a copy of the bitmap before drawing.

Use Bitmap.compress(...) to compress your bitmap to an outputstream.



回答5:

The solution of Singhak works fine. In case you need fit the size of result bitmap (perhaps for ImageView) you can expand the method as follows:

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