java itext图片大小_java – iText:降低图像质量(减少生成的PDF大小)

首先缩放图像,然后使用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));

如果在添加到PDF时仍需要原始大小,请再次将其重新缩放.

itextImage.scale(2f, 2f);

注意:此代码未经测试.

编辑回应对赏金的评论

你让我思考和寻找.似乎iText将AWT图像导入为原始图像.我认为它对待它就像BMP一样,它只是writes the pixel data using /FlateDecode,这可能远远不是最佳的.我能想到实现您的要求的唯一方法是使用ImageIO将缩放后的图像写入文件系统或将ByteArrayOutputStream写为jpeg,然后使用生成的文件/字节打开iText.

这是使用字节数组的更新示例.如果你想更多地了解压缩级别等,refer here.

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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值