加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

旋转图像90度在java

发布时间:2020-12-14 05:30:29 所属栏目:Java 来源:网络整理
导读:这个问题在这里已经有一个答案: Java: Rotating Images2 我设法将图像旋转180度,但希望顺时针旋转90度,有人可以编辑我的代码,以便进行解释.谢谢. private void rotateClockwise() { if(currentImage != null){ int width = currentImage.getWidth(); int he
这个问题在这里已经有一个答案:> Java: Rotating Images2
我设法将图像旋转180度,但希望顺时针旋转90度,有人可以编辑我的代码,以便进行解释.谢谢.
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();
    }
    }

解决方法

使用此方法.
/**
 * 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);
}

取自我的ImageTool课.

希望有帮助

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读