Rotating Java Images

I am working on a swing flickr app and thought I would share some code to help those that are new to java gui programming( like me) and get them on their way to making their killer application.

I’ll start off with my first problem,  “How do I show an Image?” After looking through Java forums and going through my Java books, I settled on using Image Icons in JLabels. The next thing I wanted to do was rotate the image 90 degrees. I used Java’s Graphics class to accomplish this. The following groovy code loads 100 JLabels containing a JPEG of Pixar’s Wall-e that I had in the same directory rotated 90 degrees.

import java.awt.image.BufferedImage
import javax.swing.*
import java.awt.*;
import java.util.*;
import java.awt.image.AffineTransformOp
import java.awt.geom.AffineTransform

class ImageButton extends JLabel{
	ImageIcon picture

public ImageButton(ImageIcon icon){
	super(icon)
	this.setBackground(Color.BLACK)
	this.setForeground(Color.BLACK)
	this.picture=icon
	this.setPreferredSize(new Dimension(120,100))
}

public void rotateImage( int angle) {
	int w = this.picture.getImage().getWidth()
	int h = this.picture.getImage().getHeight()
	BufferedImage bi = new BufferedImage(w,h,
                      BufferedImage.TYPE_INT_RGB)
	Graphics bg = bi.createGraphics();
	bg.rotate(Math.toRadians(angle), w/2, h/2);
	bg.drawImage(this.picture.getImage(),0,0,w, h,
			0,0,w, h, null);

	bg.dispose()//cleans up resources
	this.setIcon(new ImageIcon(bi))
	this.setPreferredSize(new Dimension(this.picture.getIconHeight(),
                       this.picture.getIconWidth()))
	}
}

JFrame f= new JFrame()
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
JPanel panel=new JPanel();
def img= new ImageIcon("walle.jpg")
(1..100).each{i->
	def btn=new ImageButton(new ImageIcon(img.getImage()
                        .getScaledInstance(120,100,4)))
	panel.add(btn)
	btn.rotateImage(90)//rotate the image now
	println i
}

panel.setBackground(Color.BLACK)

f.setSize(300,400)
f.getContentPane().add(panel)
f.setVisible(true)

 

My first few attempts at the code gave me out of memory Heap errors. I unknowingly had BufferedImage references hanging around.  Once I realized this, I cleaned up my code and remembered to call dispose() on the graphics bg object and everything came together quite nicely.

6 thoughts on “Rotating Java Images

  1. Thanks for the info. I would like to add that casting the width and height to floats before finding the center point of the rotation is the most accurate thing to do. Otherwise, you’ll find that there is a column/rows of pixels missing from one side of the image.

  2. I don’t know how to thank you!
    I looked for this soooo much but none worked!
    thank yooou soooo much! 🙂
    wish u be successful 😀

Leave a Reply

Your email address will not be published. Required fields are marked *