gpt4 book ai didi

java - 使用 AffineTransform Java 旋转图像时出现偏移错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:43:43 25 4
gpt4 key购买 nike

我正在尝试使用 AffineTransform 类旋转图像。但是,当旋转例如 90 度时,图像会更改其宽度和高度值,从而导致我想要删除的偏移。

这是我尝试过的

OpRotate.java

    public BufferedImage filter(BufferedImage src, BufferedImage dest) {

// Parameter auswerten
float rotationAngle = ((float) attributes.getAttributeByName("Desired rotation angle").getValue());

AffineTransform rotationTransformation = new AffineTransform();
double middlePointX = src.getHeight() / 2;
double middlePointY = src.getWidth() / 2;


rotationTransformation.setToRotation(Math.toRadians(rotationAngle), middlePointX, middlePointY);

operation = new AffineTransformOp(rotationTransformation, AffineTransformOp.TYPE_BILINEAR);

return operation.filter(src, dest);

}

将图像向右旋转 90 度后,结果如下所示:

result

最佳答案

使用 AffineTransformOp 旋转图像(在我看来)有点违反直觉...旋转本身很容易,但正如您可能已经发现的那样,困难的部分是正确平移,以便图像的左上角部分(或者它的边界框,如果是非象限旋转)旋转后完美地击中原点。

如果您需要旋转任意角度,可以使用以下非常通用的代码:

public static BufferedImage rotate(BufferedImage src, double degrees) {
double angle = toRadians(degrees); // Allows any angle

double sin = abs(sin(angle));
double cos = abs(cos(angle));

int width = src.getWidth();
int height = src.getHeight();

// Compute new width and height
double newWidth = width * cos + height * sin;
double newHeight = height * cos + width * sin;

// Build transform
AffineTransform transform = new AffineTransform();
transform.translate(newWidth / 2.0, newHeight / 2.0);
transform.rotate(angle);
transform.translate(-width / 2.0, -height / 2.0);

BufferedImageOp operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);

return operation.filter(src, null);
}

但是,如果您只想旋转 90 度的倍数,则可以使用这个稍快的变体:

public static BufferedImage rotate90(BufferedImage src, int quadrants) {
// Allows any multiple of 90 degree rotations (1, 2, 3)

int width = src.getWidth();
int height = src.getHeight();

// Compute new width and height
boolean swapXY = quadrants % 2 != 0;
int newWidth = swapXY ? height : width;
int newHeight = swapXY ? width : height;

// Build transform
AffineTransform transform = new AffineTransform();
transform.translate(newWidth / 2.0, newHeight / 2.0);
transform.quadrantRotate(quadrants);
transform.translate(-width / 2.0, -height / 2.0);

BufferedImageOp operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); // 1:1 mapping

return operation.filter(src, null);
}

关于java - 使用 AffineTransform Java 旋转图像时出现偏移错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55669270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com