我一直试图弄清楚如何翻转图片一段时间,但还没想到。
我正在使用Graphics2D
与
Image
g2d.drawImage(image, x, y, null)
我只需要一种在水平轴或垂直轴上翻转图像的方法。
如果您愿意,可以查看full source on github。
答案 0 :(得分:53)
来自http://examples.javacodegeeks.com/desktop-java/awt/image/flipping-a-buffered-image:
// Flip the image vertically
AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
tx.translate(0, -image.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
// Flip the image horizontally
tx = AffineTransform.getScaleInstance(-1, 1);
tx.translate(-image.getWidth(null), 0);
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
// Flip the image vertically and horizontally; equivalent to rotating the image 180 degrees
tx = AffineTransform.getScaleInstance(-1, -1);
tx.translate(-image.getWidth(null), -image.getHeight(null));
op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
image = op.filter(image, null);
答案 1 :(得分:27)
最简单翻转图片的方法是通过负缩放来实现。 例如:
g2.drawImage(image, x + width, y, -width, height, null);
那会水平翻转它。这将垂直翻转:
g2.drawImage(image, x, y + height, width, -height, null);
答案 2 :(得分:3)
您可以在Graphics
上使用转换,这应该可以很好地旋转图像。下面是一个示例代码,您可以使用它来实现此目的:
AffineTransform affineTransform = new AffineTransform();
//rotate the image by 45 degrees
affineTransform.rotate(Math.toRadians(45), x, y);
g2d.drawImage(image, m_affineTransform, null);
答案 3 :(得分:0)
将图像垂直旋转180度
File file = new File(file_Name);
FileInputStream fis = new FileInputStream(file);
BufferedImage bufferedImage = ImageIO.read(fis); //reading the image file
AffineTransform tx = AffineTransform.getScaleInstance(-1, -1);
tx.translate(-bufferedImage.getWidth(null), -bufferedImage.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
bufferedImage = op.filter(bufferedImage, null);
ImageIO.write(bufferedImage, "jpg", new File(file_Name));
答案 4 :(得分:0)
您需要知道图像的宽度和高度,以确保其正确缩放:
int width = image.getWidth(); int height = image.getHeight();
然后,您需要绘制它:
//Flip the image both horizontally and vertically
g2d.drawImage(image, x+(width/2), y+(height/2), -width, -height, null);
//Flip the image horizontally
g2d.drawImage(image, x+(width/2), y-(height/2), -width, height, null);
//Flip the image vertically
g2d.drawImage(image, x-(width/2), y+(height/2), width, -height, null);
无论如何,这就是我的方法。