【问题标题】:Rotating an image around a reference point [duplicate]围绕参考点旋转图像[重复]
【发布时间】:2020-07-20 18:10:50
【问题描述】:

我正在尝试使用 BufferedImage 和 AffineTransform 围绕 Java 中的参考点旋转图像,起初这似乎正是我所需要的,但事实证明它的行为不符合预期。我需要做一些基本的旋转,以 90 的倍数,所以我尝试做 getQuadrantRotateInstance,但是,如果参考点在 0,0,那么我得到一个 RasterFormatException:Transformed height (0) is less than or equal to 0.

var rotation = switch (transform) {
    case TRANS_NONE -> 0;
    case TRANS_ROT90 -> 1;
    case TRANS_ROT180 -> 2;
    case TRANS_ROT270 -> 3;
    default -> throw new NotImplementedException();
};
var transform = AffineTransform.getQuadrantRotateInstance(rotation, referenceX, referenceY);
var operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
var rotated = operation.filter(source, null);

从外观上看,图像被旋转出画布(进入负坐标),导致上述异常。

创建图像的旋转变体而不像现有解决方案那样围绕中心点进行裁剪或旋转的正确解决方案是什么?

【问题讨论】:

    标签: java rotation graphics2d image-rotation


    【解决方案1】:

    围绕中心点旋转一个角度:

    private BufferedImage rotateImage(BufferedImage buffImage, double angle) {
        double radian = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(radian));
        double cos = Math.abs(Math.cos(radian));
    
        int width = buffImage.getWidth();
        int height = buffImage.getHeight();
    
        int nWidth = (int) Math.floor((double) width * cos + (double) height * sin);
        int nHeight = (int) Math.floor((double) height * cos + (double) width * sin);
    
        BufferedImage rotatedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_INT_ARGB);
    
        Graphics2D graphics = rotatedImage.createGraphics();
    
        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        graphics.translate((nWidth - width) / 2, (nHeight - height) / 2);
        // This is the rotation around the center point - change this line
        graphics.rotate(radian, (double) (width / 2), (double) (height / 2));
        graphics.drawImage(buffImage, 0, 0, null);
        graphics.dispose();
    
        return rotatedImage;
    }
    

    要更改旋转的原点,请参阅方法rotatejavadoc


    来源:Creating simple captcha

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      相关资源
      最近更新 更多