【发布时间】:2013-12-17 18:23:18
【问题描述】:
我是 Java 新手。我现在只有 1 和 0 的 2D 二进制矩阵。我想将其保存为具有相同宽度和高度的 jpg 图像(黑白)。我怎么能意识到这一点?我尝试了下面的代码但失败了,说“java.lang.IllegalArgumentException:image == null!”请帮助我或给我更好的解决方案。非常感谢。
public static void main(String[] args) throws IOException {
//result is double[25][33] binary matrix with only 1s and 0s;
int height=result.length;
int width=result[0].length;;
byte[] data = new byte[height*width];
int k=0;
for(int i = 0;i < height;i++){
for(int j = 0; j < width; j++){
data[k]=(byte)result[i][j];
k++;
}
System.out.print("\n");
}
InputStream input = new ByteArrayInputStream(data);
BufferedImage output = ImageIO.read(input);
ImageIO.write(ouput, "jpg", new File("c:/result.jpg"));
}
【问题讨论】:
-
“我怎么能意识到这一点?” 我怀疑一种方法是将每个像素绘制到
BufferedImage.TYPE_BYTE_BINARY并保存。但不是作为 JPG,它不能准确地保留颜色。除了怀疑之外,请发布SSCCE(它只需要一些导入,并将其包装在class中)。