BufferedImage setRGB奇怪的结果

时间:2016-11-09 11:23:37

标签: java image image-processing bufferedimage

我尝试使用setRGBBufferedImage在Java中旋转图像,但是我得到了一个奇怪的结果。有谁知道为什么?

 BufferedImage pic1 = ImageIO.read(new File("Images/Input-1.bmp"));
    int width  = pic1.getWidth(null);
    int height = pic1.getHeight(null);

    double angle = Math.toRadians(90);
    double sin = Math.sin(angle);
    double cos = Math.cos(angle);
    double x0 = 0.5 * (width  - 1);     // point to rotate about
    double y0 = 0.5 * (height - 1);     // center of image

    BufferedImage pic2 = pic1;

    // rotation
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            double a = x - x0;
            double b = y - y0;
            int xx = (int) (+a * cos - b * sin + x0);
            int yy = (int) (+a * sin + b * cos + y0);

            if (xx >= 0 && xx < width && yy >= 0 && yy < height) {
                pic2.setRGB(x, y, pic1.getRGB(xx, yy));
            }
        }
    }
    ImageIO.write(pic2, "bmp", new File("Images/Output2.bmp"));

LEFT 一侧是原始图片,在 RIGHT 一侧是我的结果。有谁知道如何解决它? enter image description here

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

问题在于您使用与输入和输出相同的图像:

BufferedImage pic2 = pic1;

您必须为pic2创建另一个图像,然后进行旋转,将像素从Image1复制到Image2。

但请注意,使用getRGB和setRGB非常慢。如果你直接操作像素,它会快100倍。

相关问题