Java - 图像旋转
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12165977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - Image Rotation
提问by user1631241
I am trying to rotate image. I am using this Java code:
我正在尝试旋转图像。我正在使用此 Java 代码:
BufferedImage oldImage = ImageIO.read(new FileInputStream("C:\workspace\test\src\10.JPG"));
BufferedImage newImage = new BufferedImage(oldImage.getHeight(), oldImage.getWidth(), oldImage.getType());
Graphics2D graphics = (Graphics2D) newImage.getGraphics();
graphics.rotate(Math.toRadians(90), newImage.getWidth() / 2, newImage.getHeight() / 2);
graphics.drawImage(oldImage, 0, 0, oldImage.getWidth(), oldImage.getHeight(), null);
ImageIO.write(newImage, "JPG", new FileOutputStream("C:\workspace\test\src\10_.JPG"));
But I see strange result:
但我看到奇怪的结果:
Source:
来源:
Result:
结果:
Can you please help me with this problem?
你能帮我解决这个问题吗?
回答by Dan D.
It is not enough to switch the width and height of the image. You are rotating using the center of the image as the origin of rotation. Just try the same with a sheet of paper and you will see it works the same way. You must also move the paper a little bit, which means to apply a transform to fix this. So, immediately after the rotate call, do this:
切换图像的宽度和高度是不够的。您正在使用图像的中心作为旋转原点进行旋转。只需在一张纸上尝试相同的方法,您就会发现它的工作方式相同。您还必须稍微移动纸张,这意味着应用变换来解决此问题。因此,在旋转调用之后立即执行以下操作:
graphics.translate((newImage.getWidth() - oldImage.getWidth()) / 2, (newImage.getHeight() - oldImage.getHeight()) / 2);
回答by user1631241
The new image has different sizes because of the rotate. try this: BufferedImage newImage = new BufferedImage( oldImage.getWidth(),oldImage.getHeight(),oldImage.getType());
由于旋转,新图像具有不同的大小。试试这个: BufferedImage newImage = new BufferedImage( oldImage.getWidth(),oldImage.getHeight(),oldImage.getType());
回答by java_xof
Try getting bounds of your panel on which you do your drawing
尝试获取您在其上绘图的面板的边界
Rectangle rect = this.getBounds();
And then do:
然后做:
graphics.rotate(Math.toRadians(90), (rect.width - newImage.getWidth()) / 2, (rect.height - newImage.getHeight()) / 2);
Hope that could help Cheers!
希望可以帮助干杯!
回答by Bahramdun Adil
You can write like this it will be work.
你可以这样写它会起作用的。
BufferedImage newImage = new BufferedImage(oldImage.getWidth(), oldImage.getHeight(), oldImage.getType());
I think the place for width
and height
is wrong in your code.
我认为您的代码中的width
和位置height
是错误的。