繁体   English   中英

Java如何将图像旋转90度?

[英]Java how to rotate an image by 90 degrees?

public void rotateImage90(){
    this.redisplayImage();

    for (int x = 0; x < this.image.length; x++)
        for (int y = 0; y < this.image[0].length; y++){
            this.image[x][y] = this.image[this.image.length-1-x][y];
    }
}

我不知道如何从这里将图像旋转 90 度。 如果可以的话请帮忙

这是一种方法。 使用AffineTransForm可能有更好的方法。 此方法不会显式旋转源图像,而是旋转目标图形上下文,然后将图像写入其中。

  • 读入源图像。 在这种情况下进入buf
  • 提取维度。
  • 创建目标旋转的BufferedImageoutput ),反转源尺寸并复制图像类型( JPEG, PNG, etc )。
  • 现在获取output图像的图形上下文。
  • 由于您想围绕中心旋转,因此转换到目标中心锚点,然后以radians旋转90 degrees (Math.PI/2 )。
  • 现在准备将源图像 ( buf ) 写入 ( output ) 的旋转上下文中。 但是,锚点需要重新翻译到源文件 ( buf ) 的起始位置。 所以翻译回来但反转宽度和高度锚以匹配源文件的宽度和高度。
  • 然后将原始图像 ( buf ) 绘制到上下文旋转的缓冲图像 ( output ) 中。
  • 并将旋转后的图像( output )写入文件系统

try {
    BufferedImage buf =
            ImageIO.read(new File("f:/sourceImage.jpg"));
    int width = buf.getWidth();
    int height = buf.getHeight();
    BufferedImage output = new BufferedImage(height, width, buf.getType());
    
    Graphics2D g2d = (Graphics2D)output.getGraphics();
    g2d.translate(height/2., width/2.);
    g2d.rotate(Math.PI/2);
    g2d.translate(-width/2., -height/2.);
    g2d.drawImage(buf, 0,0,width, height,null);
    ImageIO.write(output, "JPEG", new File("f:/rotatedImage.jpg"));
} catch (Exception e) {
    e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM