先对图片进行缩放,然后使用iText打开缩放后的图片。
ImageDataFactory中有一个create方法可以接受AWT图像。首先使用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));
如需更好地缩放图像,请参阅如何使用Java调整图像大小?
如果在添加到PDF时仍需要原始大小,请将其再次缩放。
itextImage.scale(2f, 2f)
注意:此代码未经测试。
编辑,回应悬赏评论
你让我开始思考和查找。看起来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));
image.scale
等并不会改变位图数据本身,它们只会改变PDF中图像的尺寸。 - mkl