我有一个二维的双打数组,它是图像的滤波值。我想将此数组转换回BufferedImage
。如何将double[][]
投射到BufferedImage
?
BufferedImage b = new BufferedImage(arr.length, arr[0].length, 3);
Graphics c = b.getGraphics();
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
for(int i=0; i< arr.length; i++){
for (int j=0; j<arr[0].length; j++){
c.drawString(String.valueOf(arr[i][j]), i, j);
writer.print(arr[i][j]+" \t");
}
writer.println();
}
ImageIO.write(b, "jpg", new File("CustomImage.jpg"));
System.out.println("end");
当我使用imshow绘制matlab中的file-name.txt时,我可以看到我的过滤图像。但是CustomImage.jpg只包含一种颜色。知道为什么吗?
使用c.drawString(String.valueOf(arr [i] [j]),i,j)的结果:
c.drawString(String.valueOf(arr [i] [j]),0 +(i * 10),0 +(j * 10)):
Matlab plor双倍的arr首先是数组的两倍,第二个是初始的灰度缩放图像:
答案 0 :(得分:5)
您的代码
BufferedImage b = new BufferedImage(arr.length, arr[0].length, 3);
Graphics c = b.getGraphics();
for(int i = 0; i<arr.length; i++) {
for(int j = 0; j<arr[0].length; j++) {
c.drawString(String.valueOf(arr[i][j]), 0+(i*10), 0+(i*10));
}
}
ImageIO.write(b, "Doublearray", new File("Doublearray.jpg"));
System.out.println("end");
重构后
int xLenght = arr.length;
int yLength = arr[0].length;
BufferedImage b = new BufferedImage(xLenght, yLength, 3);
for(int x = 0; x < xLenght; x++) {
for(int y = 0; y < yLength; y++) {
int rgb = (int)arr[x][y]<<16 | (int)arr[x][y] << 8 | (int)arr[x][y]
b.setRGB(x, y, rgb);
}
}
ImageIO.write(b, "Doublearray", new File("Doublearray.jpg"));
System.out.println("end");
答案 1 :(得分:2)
您需要像这样设置BufferedImage
:
double[][] values;///your 2d double array
for(int y=0;y<values.length;y++){
for(int x=0;x<values[y].length;x++){
int Pixel=(int)values[x][y]<<16 | (int)values[x][y] << 8 | (int)values[x][y];
img.setRGB(x, y,Pixel);
}
}