Java save CMYK image to file
I'm trying to create image in CMYK Colorspace and after working with it, for example, painting lines etc., save it to file. Unfortunately, there isn't a lot of information in the internet about CMYK in java. 开发者_StackOverflow社区I have found only an article http://carback.us/rick/blog/?p=58. But there the Image is being saved to Pdf, using iText library. But I need it to be savet to png or jpeg file. Here is the code:
public BufferedImage createCMYKBufferedImage(double l_width, double l_height) {
ColorSpace colorSpace = SimpleCMYKColorSpace.getInstance();
ComponentColorModel l_ccm = new ComponentColorModel(colorSpace, false, false,
1, DataBuffer.TYPE_FLOAT);
int[] l_bandoff = {0, 1, 2, 3}; //Index for each color (C, is index 0, etc)
PixelInterleavedSampleModel l_sm = new PixelInterleavedSampleModel(
DataBuffer.TYPE_FLOAT,
(int)l_width, (int)l_height,
4,(int)l_width*4, l_bandoff);
WritableRaster l_raster = WritableRaster.createWritableRaster(l_sm,
new Point(0, 0));
return new BufferedImage(l_ccm, l_raster, false, null);
}
When I'm trying to save an image, i'm just calling
ImageIO.write(image, format, file);
Can anybody help me?
To write a BufferedImage as a Jpeg:
First, convert the BufferedImage to a Jpeg byte array.
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public static byte[] jpegToBytes(BufferedImage image) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
JPEGEncodeParam jparm = encoder.getDefaultJPEGEncodeParam(image);
jparm.setQuality(1F, false);
try {
encoder.encode(image, jparm);
os.close();
} catch (IOException e) {
EclipseLogging.logError(RabidPhotoPlugin.getDefault(),
RabidPhotoPlugin.PLUGIN_ID, e);
return new byte[0];
}
return os.toByteArray();
}
Next, write the byte array to a file.
public static void writePhoto(byte[] photo) {
try {
OutputStream os = new FileOutputStream('file name');
os.write(photo);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
It seems, you have a controversy in the question. Jpeg and PNG have RGB image format. For example, look http://forums.adobe.com/message/2704225. So, you have to put the source picture directly into png/jpeg or print CMYK to pdf. CMYK is a printing format, not a screen one.
精彩评论