Question

enter image description hereenter image description hereI am trying to rotate an image, somewhat it works but the problem is that it is not working properly. It's not rotating at exact I want. Image is displaying in some mix formation.

My code on button click :

RT90.addActionListener(new ActionListener() 
        {           
            @Override
            public void actionPerformed(ActionEvent arg0) 
            {
                degrees+=90;
                rotateIMG(degrees);
                repaint();
            }
        }); 

rotateIMG() code :

public void rotateIMG(double d)
    {
        BufferedImage b ;
        b=a;
        Graphics g;
        g=b.createGraphics();
        Graphics2D g2d = (Graphics2D)g;

        System.out.println(b.getWidth());
        System.out.println(b.getHeight());

        g2d.rotate(Math.toRadians(d), b.getWidth()/2, b.getHeight()/2);
        g2d.drawImage(b,0,0,null);

        ImageIcon rtimg = new ImageIcon(b);
        label.setIcon(rtimg);

    }

Any idea what's wrong in this code? Here a is buffered image which is loaded from image stack and label is JLabel using to display image.

Was it helpful?

Solution

You are overwriting the image you use as the source (b == a). You need to create a new instead.

public void rotateIMG(double d) {
    // Consider also using GraphicsConfiguration.createCompatibleImage().
    // I'm just putting here something that should work
    BufferedImage b = new BufferedImage(a.getHeight(), a.getWidth(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = b.createGraphics();

    g2d.rotate(Math.toRadians(d), a.getWidth()/2, a.getHeight()/2);
    // Note the a instead of b here
    g2d.drawImage(a, 0, 0, null);
    // Do you want to keep the old a or not?
    // a = b;
    ImageIcon rtimg = new ImageIcon(b);
    label.setIcon(rtimg);
}

OTHER TIPS

the problem is that some portion of image is cropped

Check out Rotated Icon. It will calculate the correct size of the Icon as it is rotated at various degrees.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top