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

如何使用Apache POI XWPF向docx添加图片时无需指定图片尺寸

你可以先读取图片的原始宽高,再根据需求计算等比例的目标尺寸后传入addPicture方法即可,具体实现如下:


实现步骤

  1. 读取图片原始宽高,根据指定的单一维度(宽度/高度)按比例计算另一维度值
  2. 注意处理输入流复用问题,避免读取图片尺寸后流指针偏移导致插入图片失败

代码示例

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class InsertImage {
    public static void main(String[] args) throws Exception {
        XWPFDocument docx = new XWPFDocument();
        XWPFRun run = docx.addParagraph().createRun();
        
        // 先把输入流缓存到字节数组,方便复用
        InputStream originalInputStream = /* 你的图片输入流 */;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        originalInputStream.transferTo(baos);
        byte[] imageBytes = baos.toByteArray();

        // 读取图片原始尺寸
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
        int originalWidth = bufferedImage.getWidth();
        int originalHeight = bufferedImage.getHeight();

        // 场景1:直接使用原始尺寸插入
        run.addPicture(new ByteArrayInputStream(imageBytes), 
            XWPFDocument.PICTURE_TYPE_PNG, 
            "filename", 
            Units.toEMU(originalWidth), 
            Units.toEMU(originalHeight));

        // 场景2:固定宽度为250像素,高度按比例自动计算
        int targetWidth = 250;
        int targetHeight = (int) (originalHeight * 1.0 / originalWidth * targetWidth);
        run.addPicture(new ByteArrayInputStream(imageBytes), 
            XWPFDocument.PICTURE_TYPE_PNG, 
            "filename", 
            Units.toEMU(targetWidth), 
            Units.toEMU(targetHeight));
        
        // 后续文档保存逻辑
    }
}

注意事项

  • 如果你的图片格式不被ImageIO支持,可以替换为其他图片处理工具读取宽高
  • 如果原始输入流支持mark/reset操作,也可以不用缓存字节数组,读取尺寸后调用reset方法重置流指针即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:15:04