2

I need to convert a 2D array of pixel intensity data of a grayscale image back to an image. I tried this:

BufferedImage img = new BufferedImage(
    regen.length, regen[0].length, BufferedImage.TYPE_BYTE_GRAY);  
for(int x = 0; x < regen.length; x++){
    for(int y = 0; y<regen[x].length; y++){
        img.setRGB(x, y, (int)Math.round(regen[x][y]));
    }
}
File imageFile = new File("D:\\img\\conv.bmp");
ImageIO.write(img, "bmp", imageFile);

where "regen" is a 2D double array. I am getting an output which is similar but not exact. There are few pixels that are totally opposite to what it must be (I get black color for a pixel which has a value of 255). Few gray shades are also taken as white. Can you tell me what is the mistake that I am doing?

2
  • A shot in the dark: possible rounding issue from double to int? Commented May 26, 2012 at 15:26
  • No that is not the problem i guess..most pixels are already an integer. they are just in a double array. also for the remaining few, the pixel vales are too close to an int.. for eg: i have 254.9999999999 for 255 so it must round off definitely to 255. Commented May 26, 2012 at 15:36

2 Answers 2

3

Try some code like this:

public void writeImage(int Name) {
    String path = "res/world/PNGLevel_" + Name + ".png";
    BufferedImage image = new BufferedImage(color.length, color[0].length, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < 200; x++) {
        for (int y = 0; y < 200; y++) {
            image.setRGB(x, y, color[x][y]);
        }
    }

    File ImageFile = new File(path);
    try {
        ImageIO.write(image, "png", ImageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

BufferedImage.TYPE_BYTE_GRAY is unsigned and non-indexed. Moreover,

When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the AlphaComposite documentation.

At a minimum you need to preclude sign extension and mask off all but the lowest eight bits of the third parameter to setRGB(). Sample data that reproduces the problem would be dispositive.

2 Comments

i don't think alpha component may be the issue. because even if i have all the values as 255.0 in the double array, i am still getting an image with black pixels.
You might verify the image dimensions and edit your question to include an sscce that exhibits the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.