如何在Android中旋转位图?

时间:2019-06-14 02:49:50

标签: java android-bitmap

我的位图被旋转但与原始图像重叠。

位图源

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

输出

原始位图堆叠在旋转位图的顶部。 enter image description here#问题

2 个答案:

答案 0 :(得分:0)

检查代码中的这些行

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

为什么要在返回旋转的位图之前在画布中绘制原始位图。 我想这就是问题所在。

答案 1 :(得分:0)

解决了

    public Bitmap rotateBitmap(Bitmap original, float degrees) {
        int x = original.getWidth();
        int y = original.getHeight();
        Matrix matrix = new Matrix();
        matrix.preRotate(degrees);
        Bitmap rotatedBitmap = Bitmap.createBitmap(original , 0, 0, original .getWidth(), original .getHeight(), matrix, true);
        return rotatedBitmap;
    }