开发者

how can I convert an RGB image to CMYK and vice versa in Java?

our web app let users download dynamically generated images in different formats (bmp, png and jpeg). Some of our users download the images for printing, thus we would like to allow them to choose between RGB or CMYK. Is there a way to specify the color model when creating a RenderedImage/BufferedImage? I开发者_运维技巧f not, what is the default color model and how can I change it to another? Code snippets are welcome :)

Thanks,

Olivier.


It appears that it's not simple and you'll have to either load up a color profile to do it or extend the colorspace to support CYMK.


Some image formats doesn't allow CMYK color spaces (PNG, JPEG/JFIF, GIF...) and for normal users printing in RGB is desirable.

What are the reasons you need to provide CMYK images to your customers?


To convert RGB image to CMYK image by Java, one of the easiest way is to use JAI (Java Advanced Image).

Download JAI: http://download.java.net/media/jai/builds/release/1_1_3/

DownLoad JAI ImageIO: http://download.java.net/media/jai-imageio/builds/release/1.1/

Here is the code:

public static void rgbToCmyk() throws IOException{

    BufferedImage rgbImage = ImageIO.read(new File("C://Users//Public//Pictures//Sample Pictures//RGB_IMAGE.jpg"));
    BufferedImage cmykImage = null;
    ColorSpace cpace = new ICC_ColorSpace(ICC_Profile.getInstance(RbgToCmyk.class.getClassLoader().getResourceAsStream("ISOcoated.icc")));
    ColorConvertOp op = new ColorConvertOp(rgbImage.getColorModel().getColorSpace(), cpace, null);       
    cmykImage = op.filter(rgbImage, null);

    JAI.create("filestore", cmykImage, "c:/tmp/CMYK_IMAGE.TIF", "TIFF");
}

NOTE: "ISOcoated.icc" is my ICC profile. You can get it from your printer or somewhere else.


Suggest using fromRGB() - see http://download.oracle.com/javase/1.4.2/docs/api/java/awt/color/ColorSpace.html

Sample code:

java.awt.color.ColorSpace

ColorSpace cmyk = new ColorSpace(ColorSpace.TYPE_CMYK, 4);
float[] values = cmyk.fromRGB(rgbFloatArray);

public abstract float[] fromRGB(float[] rgbvalue)

Transforms a color value assumed to be in the default CS_sRGB color space into this ColorSpace.

This method transforms color values using algorithms designed to produce the best perceptual match between input and output colors. In order to do colorimetric conversion of color values, you should use the toCIEXYZ method of the CS_sRGB color space to first convert from the input color space to the CS_CIEXYZ color space, and then use the fromCIEXYZ method of this color space to convert from CS_CIEXYZ to the output color space. See toCIEXYZ and fromCIEXYZ for further information.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜