iText:降低图像质量(减少生成的PDF大小)

ide*_*xer 7 java pdf pdf-generation itext itext7

减少使用iText新创建的PDF文件中JPEG图像大小的最佳做法是什么?(我的目标是在图像质量和文件大小之间进行权衡.)

图像创建如下:

Image image = new Image(ImageDataFactory.create(imagePath))
Run Code Online (Sandbox Code Playgroud)

我想提供一个比例因子,例如0.5,它将一行中的像素数减半.

假设我使用单个3 MB图像生成PDF.我试过image.scale(0.5f, 0.5f),但生成的PDF文件仍然大约3 MB.我预计它会变小.

因此,我猜想嵌入在PDF文件中的源图像不会被触及.但这就是我需要的:应该减少存储在磁盘上的整个PDF文件中的像素总数.

实现这一目标的最简单/推荐方法是什么?

Ben*_*gle 6

先缩放图像,然后用 iText 打开缩放后的图像。

ImageDataFactory 中有一个接受 AWT 图像的 create 方法。首先使用 AWT 工具缩放图像,然后像这样打开它:

String imagePath = "C:\\path\\to\\image.jpg";
java.awt.Image awtImage = ImageIO.read(new File(imagePath));

// scale image here
int scaledWidth = awtImage.getWidth(null) / 2;
int scaledHeight = awtImage.getHeight(null) / 2;
BufferedImage scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaledAwtImage.createGraphics();
g.drawImage(awtImage, 0, 0, scaledWidth, scaledHeight, null); 
g.dispose();

/* 
Optionally pick a color to replace with transparency.
Any pixels that match this color will be replaced by tansparency.
*/
Color bgColor = Color.WHITE;

Image itextImage = new Image(ImageDataFactory.create(scaledAwtImage, bgColor));
Run Code Online (Sandbox Code Playgroud)

有关如何缩放图像的更好提示,请参阅如何使用 Java 调整图像大小?

如果添加到 PDF 时仍需要原始尺寸,只需再次缩放即可。

itextImage.scale(2f, 2f);
Run Code Online (Sandbox Code Playgroud)

注意:此代码未经测试。


编辑回应赏金评论

你让我思考和寻找。iText 似乎将导入 AWT 图像视为原始图像。我认为它对待它与 BMP 相同,它只是使用 /FlateDecode 写入像素数据,这可能明显低于最佳值。我能想到的实现您的要求的唯一方法是使用 ImageIO 将缩放后的图像写入文件系统或 ByteArrayOutputStream 作为 jpeg,然后使用生成的文件/字节使用 iText 打开。

这是使用字节数组的更新示例。如果您想进一步了解压缩级别等,请参阅此处

String imagePath = "C:\\path\\to\\image.jpg";
java.awt.Image awtImage = ImageIO.read(new File(imagePath));

// scale image here
int scaledWidth = awtImage.getWidth(null) / 2;
int scaledHeight = awtImage.getHeight(null) / 2;
BufferedImage scaledAwtImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaledAwtImage.createGraphics();
g.drawImage(awtImage, 0, 0, scaledWidth, scaledHeight, null); 
g.dispose();

ByteArrayOutputStream bout = new ByteArrayOutputStream()
ImageIO.write(scaledAwtImage, "jpeg", bout);
byte[] imageBytes = bout.toByteArray();

Image itextImage = new Image(ImageDataFactory.create(imageBytes));
Run Code Online (Sandbox Code Playgroud)