Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

java - Convert a 2D array of doubles to a BufferedImage

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]+" ");
        }
        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): enter image description here

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...