You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在iText7中从PostgreSQL数据库读取byte[]图片到<Image>组件?

解决iText7无法识别数据库byte[]图片的问题

排查与解决方案

1. 先验证数据库中byte[]的完整性

数据库存储的字节数据可能在写入环节损坏,先导出到本地文件确认:

// 获取到数据库中的图片字节后,导出到本地测试
try (FileOutputStream fos = new FileOutputStream("test.jpg")) {
    fos.write(imageDataFileTopPage.getImageData());
} catch (IOException e) {
    e.printStackTrace();
}

打开生成的test.jpg,如果无法正常显示,说明存储到数据库的过程中数据已损坏,需要检查图片入库的代码是否完整读取了原始图片的字节流。

2. 手动指定图片格式给iText7

ImageDataFactory.create(byte[])依赖自动识别图片格式,若字节流缺少格式标识或识别失败,需手动指定类型:

// 根据实际图片格式指定,比如JPG用ImageType.JPEG,PNG用ImageType.PNG
ImageData imageTopPageData = ImageDataFactory.create(imageDataFileTopPage.getImageData(), ImageType.JPEG);
Image imageTopPage = new Image(imageTopPageData);

3. 检查实体类的数据库映射

确保PostgreSQL的bytea类型和Java实体类的byte[]字段正确映射,比如JPA注解:

@Column(columnDefinition = "bytea")
private byte[] imageData;

如果入库时是将Base64字符串转成byte[]存储的,需要先解码再传入iText7:

byte[] decodedBytes = Base64.getDecoder().decode(imageDataFileTopPage.getImageData());
ImageData imageTopPageData = ImageDataFactory.create(decodedBytes, ImageType.JPEG);

4. 确保图片被添加到文档

代码中仅创建了Image对象,需补充添加到Document的逻辑,最后关闭文档:

document.add(imageTopPage);
// 完成操作后关闭文档
document.close();

内容的提问来源于stack exchange,提问作者mjCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 19:47:09