Question

I am writing a ray tracer in java and I am trying to figure out how to write my generated image to a PNG file. So far, all the examples I have found demonstrate the use of BufferedImage to create a PNG, but they all use RGB values 0 to 255. In my code I represent each pixel colour value between 0 and 1, so for example magenta is (1, 0, 1). How can I go about writing a PNG with such values?

Thanks

Was it helpful?

Solution

If you multiply your value between 0 and 1 with 255, you'll get a number between 0 and 255.

Note: Writing a BufferedImage to a PNG file is very easy with the ImageIO API, it's just one line of code:

import javax.imageio.ImageIO;

// ...

BufferedImage image = ...;

ImageIO.write(image, "png", new File("output.png"));

OTHER TIPS

You can create a custom BufferedImage that stores its pixel data a float[].

I don't recommend it though, because some of the platform API functions will incorrectly perform color-space conversion when it is not necessary (e.g. when source and destination are both sRGB.)

Example:

ColorModel cm =
    new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
                            false, false, Transparency.OPAQUE,
                            DataBuffer.TYPE_FLOAT);
WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
BufferedImage img = new BufferedImage(cm, raster, false, null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top