首页 > 解决方案 > 坐标越界

问题描述

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

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 有问题。如果我评论它,我的错误就会消失,但程序没有做正确的事情。

标签: javaimagergbindexoutofboundsexception

解决方案


您尝试修改的图像似乎未调整大小。尝试用双倍宽度实例化一个新的干净缓冲图像

在这里的第一次迭代:

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);

推荐阅读