坐标越界

coordinates out of bound

我做了一个镜像镜像的程序,但是下面的代码给出了一个错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 
Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.setDataElements(Unknown Source)
at java.awt.image.BufferedImage.setRGB(Unknown Source)
at algoritm.MirrorImage.applyAlgoritm(MirrorImage.java:43)
at ImageProcess.main(ImageProcess.java:36)

这里是源代码:

package algoritm;   
import java.awt.image.BufferedImage;   
public class MirrorImage implements Algoritm{   
private BufferedImage bufferedImage;
private int width;
private int height;
//getter si setter
    public MirrorImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;

    }

    public BufferedImage getBufferedImage() {
        return bufferedImage;
    }

    public void setBufferedImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }

    public void applyAlgoritm() {
        width = bufferedImage.getWidth();
        height = bufferedImage.getHeight();
        for(int y = 0; y < height; y++){
            for(int lx = 0, rx = width*2 - 1; lx < width; lx++, rx--){
                int p = bufferedImage.getRGB(lx,y);
                bufferedImage.setRGB(lx, y, p);
                bufferedImage.setRGB(rx, y, p);
              }
        }
    }
}

我认为第二个 setRGB 有问题。如果我评论它,我的错误就消失了,但程序没有做正确的事情。

您尝试修改的图片似乎没有调整大小。 尝试用双倍宽度

实例化一个新的干净缓冲图像

在这里第一次迭代:

width = bufferedImage.getWidth();
rx = width*2 - 1;
  ...
  bufferedImage.setRGB(rx, y, p);

rx 超出范围,请尝试在您的构造函数中创建一个新的干净图像

BufferedImage newImage = new BufferedImage(2 * bufferedImage.getWidth(),  bufferedImage.getHieght(), BufferedImage.TYPE_INT_ARGB);

并在这个上面镜像,所以在你的循环中

//read from the old one 
int p = bufferedImage.getRGB(lx,y);

// and write in the new one
newImage.setRGB(lx, y, p);
newImage.setRGB(rx, y, p);
setRGB(int x, int y, int rgb)
Sets a pixel in this BufferedImage to the specified RGB value.

我不是一个普通的 java 程序员,但是当我阅读 setRgb() 函数的文档时,正如您在上面看到的那样,x 和 y 保存像素的坐标,其中 rgb 是新的像素值。当我查看您的 for 循环时,在第二个循环中您有 bufferedImage.setRGB(rx, y, p);,您试图将 rx 设置为开头的 x 值 rx = width*2 - 1; 并且毫无疑问这超过了图像宽度。所以,我想你需要重新考虑你的算法来解决你的问题。