How to write PNG files in java using pixel RGB values 0 to 1?

梦想与她 提交于 2019-12-10 22:06:26

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4845646/how-to-write-png-files-in-java-using-pixel-rgb-values-0-to-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!