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

在MS Word特定文字后插入图片:代码正常运行但图片未显示

问题排查与修复方案

1. 图片文件夹读取校验缺失

new File("C:\\Users\\Screenshots\\").listFiles()可能返回null(比如路径错误、无访问权限、文件夹为空),此时后续无法获取有效图片路径,自然无法插入图片。必须先添加校验逻辑:

File imageDir = new File("C:\\Users\\Screenshots\\");
// 过滤仅读取PNG格式图片
File[] images = imageDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png"));
if (images == null || images.length == 0) {
    System.out.println("未找到有效PNG图片或文件夹不可访问");
    return;
}

2. Run遍历的并发修改问题

直接遍历paragraph.getRuns()的同时插入新Run,会破坏原集合的遍历结构,导致部分Run被跳过或索引错位。需先将Run列表复制为新集合再遍历:

List<XWPFRun> runs = new ArrayList<>(paragraph.getRuns()); // 复制集合避免遍历中修改原数据

3. 图片尺寸单位错误

addPicture的宽高参数为EMU单位(不是像素),直接填200像素会导致图片显示极小,肉眼几乎不可见。需要将像素转换为EMU(1像素≈9525 EMU):

int widthEmu = 200 * 9525;
int heightEmu = 200 * 9525;
imageRun.addPicture(imgStream, XWPFDocument.PICTURE_TYPE_PNG, imgFile, widthEmu, heightEmu);

4. 图片输入流未关闭

打开的FileInputStream未关闭可能导致资源泄漏,甚至影响图片写入文档。使用try-with-resources语法自动关闭流:

try (FileInputStream imgStream = new FileInputStream(imgFile)) {
    imageRun.addPicture(imgStream, XWPFDocument.PICTURE_TYPE_PNG, imgFile, widthEmu, heightEmu);
}

修复后的完整代码

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ImageWord {
    public static void main(String[] args) throws Exception {
        // 用try-with-resources自动关闭文档和输出流
        try (XWPFDocument doc = new XWPFDocument(new FileInputStream("C:\\test\\image.doc"));
             FileOutputStream out = new FileOutputStream("C:\\test\\images.doc")) {

            List<XWPFParagraph> paragraphs = doc.getParagraphs();
            int imageCounter = 0;

            // 读取并过滤图片文件夹
            File imageDir = new File("C:\\Users\\Screenshots\\");
            File[] images = imageDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png"));
            if (images == null || images.length == 0) {
                System.out.println("未找到有效PNG图片或文件夹不可访问");
                return;
            }

            for (XWPFParagraph paragraph : paragraphs) {
                List<XWPFRun> runs = new ArrayList<>(paragraph.getRuns());
                for (XWPFRun run : runs) {
                    String text = run.getText(0);
                    if (text != null && text.contains("word")) {
                        int insertIndex = runs.indexOf(run) + 1;
                        XWPFRun imageRun = paragraph.insertNewRun(insertIndex);

                        String imgFile = images[imageCounter].getAbsolutePath();
                        int widthEmu = 200 * 9525;
                        int heightEmu = 200 * 9525;
                        
                        try (FileInputStream imgStream = new FileInputStream(imgFile)) {
                            imageRun.addPicture(imgStream, XWPFDocument.PICTURE_TYPE_PNG, imgFile, widthEmu, heightEmu);
                        }

                        imageRun.addBreak();
                        imageCounter = (imageCounter + 1) % images.length; // 循环复用图片
                    }
                }
            }

            doc.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:00:49