使用AffineTransform进行Java图像旋转会输出黑色图像,但在调整大小时效果很好 [英] Java image rotation with AffineTransform outputs black image, but works well when resized
问题描述
我只是想将JPG文件旋转90度。但是我的代码输出完全黑色的图像( BufferedImage
)。
I am just trying to rotate a JPG file by 90 degrees. However my code outputs image (BufferedImage
) that is completely black.
这是重现的方式:(下载3 .jpg 此处 )
Here's the way to reproduce: (Download 3.jpg here)
private static BufferedImage transform(BufferedImage originalImage) {
BufferedImage newImage = null;
AffineTransform tx = new AffineTransform();
tx.rotate(Math.PI / 2, originalImage.getWidth() / 2, originalImage.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BICUBIC);
newImage = op.filter(originalImage, newImage);
return newImage;
}
public static void main(String[] args) throws Exception {
BufferedImage bi = transform(ImageIO.read(new File(
"3.jpg")));
ImageIO.write(bi, "jpg", new File("out.jpg"));
}
这里有什么问题?
(如果我将这个黑色输出 BufferedImage
提供给图像缩放器库,它会很好地调整大小,原始图像仍然存在。)
(if I give this black output BufferedImage
to a image resizer library, it gets resized well, original image is still there.)
推荐答案
将新的BufferedImage传递给filter()方法,而不是让它创建自己的作品(不是完全黑色)。
Passing a new BufferedImage into the filter() method rather than letting it create its own works (not completely black).
此外,转换似乎无法正常工作,图像最终在目标中偏移。我能够通过手动应用必要的翻译来修复它,按相反顺序记录这些工作,并在目标图像中宽度=旧高度,高度=旧宽度。
Also the transform did not appear to work correctly, the image ended up being offset in the destination. I was able to fix it by manually applying the necessary translations, note these work in reverse order, and in the destination image the width = the old height, and height = the old width.
AffineTransform tx = new AffineTransform();
// last, width = height and height = width :)
tx.translate(originalImage.getHeight() / 2,originalImage.getWidth() / 2);
tx.rotate(Math.PI / 2);
// first - center image at the origin so rotate works OK
tx.translate(-originalImage.getWidth() / 2,-originalImage.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// new destination image where height = width and width = height.
BufferedImage newImage =new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), originalImage.getType());
op.filter(originalImage, newImage);
filter()的javadoc声明它会为你创建一个BufferedImage,我仍然不确定为什么这不起作用,这里一定有问题。
The javadoc for filter() states that it will create a BufferedImage for you, I'm still unsure why this does not work, there must be an issue here.
If the destination image is null, a BufferedImage is created with the source ColorModel.
这篇关于使用AffineTransform进行Java图像旋转会输出黑色图像,但在调整大小时效果很好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!