我正在尝试在 CMYK 色彩空间中创建图像,并在使用它之后,例如绘制线条等,将其保存到文件中。不幸的是,互联网上没有很多关于 java 中的 CMYK 的信息。我只找到一篇文章http://carback.us/rick/blog/?p=58 。但图像正在使用 iText 库保存为 Pdf。但我需要将其保存为 png 或 jpeg 文件。这是代码:
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);
}
当我尝试保存图像时,我只是调用
ImageIO.write(image, format, file);
有人可以帮我吗?
最佳答案
将 BufferedImage 写入 Jpeg:
首先,将 BufferedImage 转换为 Jpeg 字节数组。
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();
}
接下来,将字节数组写入文件。
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();
}
}
关于Java将CMYK图像保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5262514/