Java - 图像旋转 [英] Java - Image Rotation
问题描述
我正在尝试旋转图像。我使用这个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:\\\\\\ space\\\\\\\\\\\\\\\\\\'));
但我看到奇怪的结果:
来源:
结果:
**结果图:** http://s14.postimage.org/cjut935ip/image.jpg
你能帮我吗有这个问题吗?
切换图片的宽度和高度是不够的。您正在旋转使用图像的中心作为旋转的起点。只要试着用一张纸做同样的事情,你会发现它的工作原理是一样的。您还必须稍微移动纸张,这意味着应用转换来解决此问题。因此,在循环调用之后立即执行此操作:
graphics.translate((newImage.getWidth() - oldImage.getWidth( ))/ 2,(newImage.getHeight() - oldImage.getHeight())/ 2);
I am trying to rotate image. I am using this Java code:
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:
**Result image:** http://s14.postimage.org/cjut935ip/image.jpg
Can you please help me with this problem?
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);
这篇关于Java - 图像旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!