Rotate Image in Java
In this tutorial, I am writing simple swing program about, How to Rotate Image in Java on Swing Window. The example program were tested and output were shared in the same post.
ImageRotate.java
package com.dineshkrish.swing; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; /** * * @author Dinesh Krishnan * */ public class ImageRotate extends JPanel { private File imageFile; public ImageRotate(String fileName) { if(fileName != null && !fileName.isEmpty()) { imageFile = new File(fileName); } } @Override public void paintComponent(final Graphics g) { try { // Loading the Image BufferedImage image = ImageIO.read(imageFile); AffineTransform af = AffineTransform.getTranslateInstance(100, 100); // Rotating the Image in 90 degree af.rotate(Math.toRadians(90), image.getWidth() /2, image.getHeight()/2); Graphics2D graphics2d = (Graphics2D)g; graphics2d.drawImage(image, af, null); graphics2d.dispose(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static void main(String[] args) { String windowTitle = "Image Rotate"; // You can change the Image file and Path accordingly ImageRotate panel = new ImageRotate("java.png"); // Window JFrame frame = new JFrame(); frame.setTitle(windowTitle); frame.setSize(400, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Adding the Panel to Window frame.add(panel); frame.setVisible(true); } }
Output
References
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet