我正在尝试在java中运行此代码。但是,当我打开文件时,它完全是空的。我不明白为什么,需要帮助。 对于某些图像处理目的,我尝试用RGB值来提取每个像素。为什么我的文件是空的?
class Pixel {
BufferedImage image;
int width;
int height;
public Pixel() {
try {
File input = new File("originalLeopard.jpg");
image = ImageIO.read(input);
width = image.getWidth();
height = image.getHeight();
BufferedWriter writer = new BufferedWriter(new FileWriter("pixy.txt"));
for(int y=0; y < height; y++){
for(int x=0; x <width; x++){
Color c = new Color(image.getRGB(y, x));
writer.write(y + " " + x +" "+ c.getRed()+ " " + c.getGreen()+ " "+ c.getBlue()+"\n");
}
}
writer.close();
}
catch (Exception e) {
}
}
static public void main(String args[]) throws Exception
{
Pixel obj = new Pixel();
}
}
答案 0 :(得分:5)
您正在捕获所有异常但未打印出堆栈跟踪。这会告诉你你的代码正在抛出:
java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)
at java.awt.image.BufferedImage.getRGB(Unknown Source)
at com.unionsystemsltd.optimus.secure.jwt.Pixel.<init>(Pixel.java:35)
at com.unionsystemsltd.optimus.secure.jwt.Pixel.main(Pixel.java:51)
答案 1 :(得分:1)
这似乎是因为你写了image.getRGB(y,x)
而不是image.getRGB(x,y)