Search code examples
javarotationimage-rotation

Java Rotate Image function


How can I make this code work??

public class Tutorial extends Applet{

/////////////////DRAWING IMAGES TO THE SCREEN///////////////////////
private Image spiral = null;

public void paint (Graphics g){
    this.setSize(640, 480);

    if (spiral == null){
        spiral = getImage("spiral.jpg");
        spiral.rotateImage(45, this);  //It says that rotateImage is undefined for the Image
    }

    Graphics2D g2 = (Graphics2D)g;
    g2.drawImage(spiral, 25, 50, this);
}

public Image getImage(String path){
    Image tempImage = null;
    try
    {
        URL imageURL = Tutorial.class.getResource(path);
        tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
    }
    catch (Exception e)
    {
        System.out.println("An error occured - " + e.getMessage());
    }
    return tempImage;
}

////////////////////////////////////////////////////////////////////

///////////////////IMAGE ROTATION /////////////////////////////////

public void rotateImage(double degrees, ImageObserver o){
    ImageIcon icon = new ImageIcon(this.spiral);
    BufferedImage blankCanvas = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D)blankCanvas.getGraphics();
    g2.rotate(Math.toRadians(degrees), icon.getIconWidth()/2, icon.getIconHeight()/2);
    g2.drawImage(this.spiral, 0, 0, o);
    this.spiral = blankCanvas;
}
/////////////////////////////////////////////////////////////////
}

I know that I have to change either the method rotateImage or the Image type but I can't really succeed. I'm a little bit off the boat in this subject. Any help?


Solution

  • Change

    if (spiral == null){
        spiral = getImage("spiral.jpg");
        spiral.rotateImage(45, this);
    }
    

    To

    if (spiral == null){
        spiral = getImage("spiral.jpg");
        rotateImage(45, this);
    }
    

    since rotateImage is your own method not an Image method