Search code examples
javaandroid-bitmap

How to rotate bitmap in android?


My bitmap is rotated but is overlaped with original image.

Bitmap source

public void onImageAvailable(ImageReader reader) {
            final Image image = reader.acquireNextImage();
//            final Image image = reader.acquireLatestImage();
            final ByteBuffer yuvBytes = imageToByteBuffer(image);

            // Convert YUV to RGB
            final RenderScript rs = RenderScript.create(MainActivity.this);

            Bitmap        bitmap     = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
            final Allocation allocationRgb = Allocation.createFromBitmap(rs, bitmap);

            final Allocation allocationYuv = Allocation.createSized(rs, Element.U8(rs), yuvBytes.array().length);
            allocationYuv.copyFrom(yuvBytes.array());

            ScriptIntrinsicYuvToRGB scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
            scriptYuvToRgb.setInput(allocationYuv);
            scriptYuvToRgb.forEach(allocationRgb);

            allocationRgb.copyTo(bitmap);
            int rotation = MainActivity.this.getWindowManager().getDefaultDisplay().getRotation();
            int x = bitmap.getWidth();
            int y = bitmap.getHeight();
            Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, y, x, true);
            Bitmap rotatedBitmap = rotateBitmap(bitmap1, getOrientation(rotation));

RotatedBitmapFunction

public Bitmap rotateBitmap(Bitmap original, float degrees) {
        int width = original.getWidth();
        int height = original.getHeight();

        Matrix matrix = new Matrix();
        matrix.preRotate(degrees);

        Bitmap rotatedBitmap = Bitmap.createBitmap(original, 0, 0, width, height, matrix, true);
        Canvas canvas = new Canvas(rotatedBitmap);
        canvas.drawBitmap(original, 5.0f, 0.0f, null);

        return rotatedBitmap;
    }

Output

The original bitmap is stacked on top of rotatedbitmap. enter image description here#Problem


Solution

  • Check these lines in your code

     Canvas canvas = new Canvas(rotatedBitmap);
    canvas.drawBitmap(original, 5.0f, 0.0f, null);
    

    Why you are drawing the origin bitmap in the canvas just before returning the rotated Bitmap. I guess this is the issue.