gpt4 book ai didi

java - 在java中将二维二进制矩阵转换为黑白图像

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:17:48 25 4
gpt4 key购买 nike

我是 java 新手。我现在有只有 1 和 0 的二维二进制矩阵。我想将它保存为具有相同宽度和高度的 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"));

}

最佳答案

这是一个创建 30x30 方格框的简单示例:

enter image description here

public static void main(String... args) throws IOException {
int w = 30, h = 30;

// create the binary mapping
byte BLACK = (byte)0, WHITE = (byte)255;
byte[] map = {BLACK, WHITE};
IndexColorModel icm = new IndexColorModel(1, map.length, map, map, map);

// create checkered data
int[] data = new int[w*h];
for(int i=0; i<w; i++)
for(int j=0; j<h; j++)
data[i*h + j] = i%4<2 && j%4<2 || i%4>=2 && j%4>=2 ? BLACK:WHITE;

// create image from color model and data
WritableRaster raster = icm.createCompatibleWritableRaster(w, h);
raster.setPixels(0, 0, w, h, data);
BufferedImage bi = new BufferedImage(icm, raster, false, null);

// output to a file
ImageIO.write(bi, "jpg", new File("C:\\Users\\user\\Desktop\\test.jpg"));
}

编辑:

对于您正在做的事情,您实际上不需要创建自己的 ImageColorModel,您可以使用内置类型:BufferedImage.TYPE_BYTE_GRAY 或 TYPE_BYTE_BINARY。这是一个更好的示例,展示了如何使用灰度来获得方格框:

enter image description here

public static void main(String... args) throws IOException {
int w = 40, h = 40, divs = 5;

BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = bi.getRaster();

for(int i=0; i<w; i++)
for(int j=0; j<h; j++)
raster.setSample(i,j,0,128+(int)(127*Math.sin(Math.PI*i/w*divs)*Math.sin(Math.PI*j/h*divs)));

ImageIO.write(bi, "jpg", new File("C:\\Users\\user\\Desktop\\test.jpg"));
}

关于java - 在java中将二维二进制矩阵转换为黑白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20321606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com