2016-11-09 19 views
2

我已经尝试使用setRGBBufferedImage旋转Java中的图片,但我得到一个奇怪的结果。有没有人知道为什么?的BufferedImage setRGB奇怪的结果

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

不能到位旋转图像。你制作另一个单独的旋转图像。如果要将图像旋转90度,则不必执行旋转数学运算。只需将x坐标复制到新的y坐标,并将y坐标复制到新的x坐标。 –

回答

1

的问题是,您使用的相同的图像作为输入,并且输出:

的BufferedImage PIC2 = PIC1;

您必须为PIC2另一个图像,然后做旋转,复制从图像1到图像2的像素。

但是请注意,在使用的getRGB和setRGB它非常缓慢。如果直接操作像素,速度会快100倍。

+0

谢谢,我没有注意到这个错误:D现在它工作。以及关于setRBG和getRGB ......我知道它们很慢......但我不知道如何将图像转换为像素[] []。我搜索了互联网上的每一个地方,以及我看到的所有内容,就是如何从图像中获取数组1D,我的意思是像像素[]。但我需要像像素[] []二维数组,我不知道如何获得它....你能帮助我,并与此? :d –

+0

在这其中您创建一个像素的图像: http://stackoverflow.com/questions/8856569/how-to-get-the-array-of-pixel-values-for-an-image-in -java-使用-的getRGB –