我目前正在尝试创建一个用纯色填充的形状,然后将其输出为PNG。这是我的代码。
void CreateRedImage(int xSize, int ySize, String FileName){
BufferedImage bf = new BufferedImage(xSize, ySize, BufferedImage.TYPE_INT_RGB);
Color color = new Color(225, 000, 000);
File f = new File(FileName + ".png");
bf.setRGB(xSize, ySize, color.getRGB());
try {
ImageIO.write(bf, "PNG", f);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}不幸的是,当我运行我的代码时,我得到了这个错误消息。
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.IntegerInterleavedRaster.setDataElements(IntegerInterleavedRaster.java:301)
at java.awt.image.BufferedImage.setRGB(BufferedImage.java:988)
at ImageCreation.CreateBlueImage(ImageCreation.java:53)
at Main.main(Main.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)现在,我知道问题出在这条线上:
bf.setRGB(xSize, ySize, color.getRGB());我还不能弄清楚为什么我的代码不能工作。有谁有主意吗?
发布于 2013-03-12 23:54:46
如果您查看BufferedImage的setRGB(int x,int y,int rgb)的docs,它会显示:-
将此BufferedImage中的像素设置为指定的RGB值。假设像素在默认的RGB颜色模型、TYPE_INT_ARGB和默认的sRGB颜色空间中。
它还说
如果坐标不在边界内,则可能会抛出ArrayOutOfBoundsException。但是,不能保证进行显式边界检查。
这意味着您的xSize和ySize不在BufferedImage的边界内。
更新:-
再次从文档中,如果您仔细查看您碰巧使用的BufferedImage构造函数的签名,您将看到以下内容:
public BufferedImage(int width, int height, int imageType)这意味着,在您的例子中,xSize和ySize就是width和height,而您的BI不一定要有 case (xSize,ySize)。我希望你能明白这一点。
发布于 2013-03-12 23:49:37
bf.setRGB(xSize, ySize, color.getRGB());setRGB正在设置单个像素,x坐标为0 ..xSize - 1,y坐标如wise。
int c = color.getRGB();
for (int x = 0; x < xSize; ++x) {
for (int y = 0; y < ySize; ++y) {
bf.setRGB(x, y, color);
}
}或
Graphics2D g = bf.createGraphics();
g.setColor(color);
g.fillRect(0, 0, xSize, ySize);
g.dispose();或者使用BufferedImage的光栅效果更好。
发布于 2013-03-12 23:51:25
您可能需要类似于bf.getGraphics().fillRect(...)
https://stackoverflow.com/questions/15365645
复制相似问题