Rotate the image 90 degrees in Java

There is already an answer to this question: > java: rotating Images2

private void rotateClockwise()
    {
        if(currentImage != null){
            int width = currentImage.getWidth();
            int height = currentImage.getHeight();
            OFImage newImage = new OFImage(width,height);
            for(int y = 0; y < height; y++) {
                for(int x = 0; x < width; x++) {
                    newImage.setPixel( x,height-y-1,currentImage.getPixel(x,y));
                }
        }
            currentImage = newImage;
            imagePanel.setImage(currentImage);
            frame.pack();
    }
    }

Solution

Use this method

/**
 * Rotates an image. Actually rotates a new copy of the image.
 * 
 * @param img The image to be rotated
 * @param angle The angle in degrees
 * @return The rotated image
 */
public static Image rotate(Image img,double angle)
{
    double sin = Math.abs(Math.sin(Math.toradians(angle))),cos = Math.abs(Math.cos(Math.toradians(angle)));

    int w = img.getWidth(null),h = img.getHeight(null);

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

    BufferedImage bimg = toBufferedImage(getEmptyImage(neww,newh));
    Graphics2D g = bimg.createGraphics();

    g.translate((neww-w)/2,(newh-h)/2);
    g.rotate(Math.toradians(angle),w/2,h/2);
    g.draWrenderedImage(toBufferedImage(img),null);
    g.dispose();

    return toImage(bimg);
}

From my imagetool class

I hope it helps

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>