Отразить изображение с помощью Graphics2D - программирование
Подтвердить что ты не робот

Отразить изображение с помощью Graphics2D

Я пытался выяснить, как перевернуть изображение какое-то время, но пока не понял.

Я использую Graphics2D для рисования изображения с помощью

g2d.drawImage(image, x, y, null)

Мне просто нужен способ перевернуть изображение по горизонтальной или вертикальной оси.

Если вы хотите, вы можете посмотреть полный источник на github (ссылка)

EDIT: Woops, я хотел поставить "flip" в заголовок, а не "вращать".

4b9b3361

Ответ 1

Из 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);

Ответ 2

самый простой способ переворачивания изображения - это отрицательное масштабирование. Пример:

g2.drawImage(image, x + width, y, -width, height, null);

Это будет переворачивать его по горизонтали. Это перевернет его по вертикали:

g2.drawImage(image, x, y + height, width, -height, null);

Ответ 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); 

Ответ 4

Повернуть изображение Вертикальное 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));