rotating image

Hi,

I am able to rotate the image with the code below. However, when I rotate it several times the image moves off center. I guess it's because it rotates it with respect to width and height of the image, but that changes on each rotation. Does anyone know how to make it to stay in center?

import javax.imageio.ImageIO;

import javax.swing.*;

import java.awt.*;

import java.io.*;

import java.awt.event.*;

import java.awt.geom.AffineTransform;

import java.awt.image.AffineTransformOp;

import java.awt.image.BufferedImage;

publicclass tester{

static JLabel labelImage;

publicstaticvoid main(String[] args)

{

JFrame f =new JFrame();

Container c = f.getContentPane();

try

{

labelImage =

new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg"))));

c.add(labelImage,BorderLayout.CENTER);

JButton button =new JButton("Flip V");

button.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e)

{

Image img = ((ImageIcon)labelImage.getIcon()).getImage();

labelImage.setIcon(new ImageIcon(rotate(img,1)));

}

});

c.add(button,BorderLayout.SOUTH);

}catch(IOException e){}

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setSize(new Dimension(500,500));

f.setVisible(true);

}

publicstatic Image rotate(Image src,int direction)

{

AffineTransform tx =new AffineTransform();

BufferedImage bufferedImage = createBufferedImage(src);

tx.rotate(direction*Math.PI/2, bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);

AffineTransformOp op =new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

bufferedImage = op.filter(bufferedImage,null);

return bufferedImage;

}

publicstatic BufferedImage createBufferedImage(Image image){

if(imageinstanceof BufferedImage)

return (BufferedImage)image;

int w = image.getWidth(null);

int h = image.getHeight(null);

BufferedImage bi =new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

Graphics2D g = bi.createGraphics();

g.drawImage(image, 0, 0,null);

g.dispose();

return bi;

}

}

[4278 byte] By [forumusera] at [2007-10-3 9:34:08]
# 1
Not, only it is off center but the image is trimmed on the sides.
forumusera at 2007-7-15 4:49:24 > top of Java-index,Security,Cryptography...
# 2

http://forum.java.sun.com/thread.jspa?threadID=487900&messageID=2286191

Just in case anyone needs it

public static BufferedImage rotateImage(BufferedImage image, double angle) {

double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));

int w = image.getWidth(), h = image.getHeight();

int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);

GraphicsConfiguration gc = getDefaultConfiguration();

BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);

Graphics2D g = result.createGraphics();

g.translate((neww-w)/2, (newh-h)/2);

g.rotate(angle, w/2, h/2);

g.drawRenderedImage(image, null);

g.dispose();

return result;

}

forumusera at 2007-7-15 4:49:24 > top of Java-index,Security,Cryptography...