【问题标题】:Rotating a bufferedImage 90 degrees将缓冲图像旋转 90 度
【发布时间】:2020-07-06 09:21:09
【问题描述】:

我希望将从文件加载的图像旋转 90 度。我有代码,但是当我使用它时,我收到一条错误消息,指出坐标超出范围。任何帮助将不胜感激。

这是我目前写的方法:

public void rotateImage(OFImage image) {
    if (currentImage != null) {
        int width = image.getWidth();
        int height = image.getHeight();
        OFImage newImage = new OFImage(width, height);

        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Color col = image.getPixel(i, j);
                newImage.setPixel(height - j - 2, i, col);
            }
        }
        image = newImage;
    }
}

【问题讨论】:

    标签: java image rotation bufferedimage graphics2d


    【解决方案1】:

    当您将图像旋转一定角度时,生成的图像会比原始图像大。旋转45度时得到的最大图像尺寸:

    创建新图像时,必须根据旋转后的大小设置其尺寸:

    public BufferedImage rotateImage(BufferedImage image, double angle) {
        double radian = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(radian));
        double cos = Math.abs(Math.cos(radian));
    
        int width = image.getWidth();
        int height = image.getHeight();
    
        int nWidth = (int) Math.floor((double) width * cos + (double) height * sin);
        int nHeight = (int) Math.floor((double) height * cos + (double) width * sin);
    
        BufferedImage rotatedImage = new BufferedImage(
                nWidth, nHeight, BufferedImage.TYPE_INT_ARGB);
    
        // and so on...
    
        return rotatedImage;
    }
    

    另见:Rotate a buffered image in Java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2019-07-29
      • 2013-02-13
      • 2013-04-22
      相关资源
      最近更新 更多