使用Graphics2D翻转图像

Fuz*_*uze 21 java swing image graphics2d

我一直想弄清楚如何翻转图像一段时间,但还没想到.

我使用Graphics2D画一个Image

g2d.drawImage(image, x, y, null)
Run Code Online (Sandbox Code Playgroud)

我只需要一种在水平轴或垂直轴上翻转图像的方法.

如果你想要,你可以看看github上的完整源代码.

I82*_*uch 55

来自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);
Run Code Online (Sandbox Code Playgroud)


hsi*_*kar 29

翻转图像的最简单方法是对其进行负缩放.例:

g2.drawImage(image, x + width, y, -width, height, null);
Run Code Online (Sandbox Code Playgroud)

那会水平翻转它.这将垂直翻转:

g2.drawImage(image, x, y + height, width, -height, null);
Run Code Online (Sandbox Code Playgroud)

  • 这几乎是好的.它应该像g2.drawImage(image,x + height,y,width,-height,null); 这是因为负刻度将图像向左移动,所以你必须补偿这种运动. (13认同)
  • 是的+1 @TG是为了平衡消极性. (2认同)