I have used BufferedImage class to generate images from pdf. I am getting 8-bit RGBA by using the below-mentioned snippet, but I was unable to convert it to 16 bpc RGBA.
int page = 0;
BufferedImage bim = new BufferedImage(100, 100, BufferedImage.TYPE_USHORT_565_RGB);
bim = pdfRenderer.renderImage(page);
String fileName = OUTPUT_DIR + "image-" + page + ".png";
ImageIOUtil.writeImage(bim, fileName, 1);
To create a 16 bit per sample (or channel) BufferedImage
and store it as a PNG, you can use the following code:
ComponentColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_USHORT);
BufferedImage image = new BufferedImage(colorModel, colorModel.createCompatibleWritableRaster(100, 100), colorModel.isAlphaPremultiplied(), null);
if (!ImageIO.write(image, "PNG", new File("test.png"))) {
System.err.println("Could not write PNG: " + image);
}
From the code, I'm assuming you are using PDFBox. If you are using PDFBox, you can use ImageIOUtil.writeImage
instead of ImageIO.write
. But you probably want to set the DPI to something more reasonable than 1
... 😉
Also note that image = pdfRenderer.renderImage(page)
in your code will replace the image, so you can't use that. Try using the renderPageToGraphics(int, Graphics2D)
method instead:
ComponentColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_USHORT);
BufferedImage image = new BufferedImage(colorModel, colorModel.createCompatibleWritableRaster(100, 100), colorModel.isAlphaPremultiplied(), null);
Graphics2D g = image.createGraphics();
try {
pdfRenderer.renderPageToGraphics(page, g);
}
finally {
g.dispose();
}
if (!ImageIOUtil.writeImage(image, test.png, 72))) {
System.err.println("Could not write PNG: " + image);
}