java - 坐标越界
问题描述
我制作了一个镜像图像的程序,但下面的代码给出了错误:
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);
推荐阅读
- javascript - 尝试进行更清晰的异步 JSON 翻译调用
- javascript - 开玩笑的反应 onSubmit 不包括方法
- java - Java - 在导航到具有相同 html 模板的不同页面时断言类包含文本
- php - 使用 vsmoraes/laravel-pdf 包在 laravel 中返回带有变量的视图
- latex - 未定义的控制序列 \chapter
- sql - 在 SELECT 语句中声明和使用变量
- javascript - JavaScript强制点击下载?
- angular6 - 通过 Angular 应用程序代理 api 服务器
- c# - LINQ 到列表
- cocoa - 当我使用 NSView.dataWithPDF(inside:) 时如何影响背景颜色