Convert a 2D array of doubles to a BufferedImage

2019-02-19 07:30发布

问题:

I've got a two-dimensional array of doubles which is filtered values of an image. I want to convert this array back to a BufferedImage. How is it possible to cast an double[][] to a 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");

When I am plot the file-name.txt in matlab with imshow I can see my filtered image. However the CustomImage.jpg contains just one color. Any idea why?

THe result with c.drawString(String.valueOf(arr[i][j]), i, j):

c.drawString(String.valueOf(arr[i][j]), 0+(i*10), 0+(j*10)):

Matlab plor the double of arr first the double of arrays and second the initial gray scaled image:

回答1:

Your Code

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");

After Refactoring

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");


回答2:

You need to set the BufferedImagelike this:

 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);
   }

 }