如何使用Apache POI XWPF向docx添加图片时无需指定图片尺寸
你可以先读取图片的原始宽高,再根据需求计算等比例的目标尺寸后传入addPicture方法即可,具体实现如下:
实现步骤
- 读取图片原始宽高,根据指定的单一维度(宽度/高度)按比例计算另一维度值
- 注意处理输入流复用问题,避免读取图片尺寸后流指针偏移导致插入图片失败
代码示例
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
相关产品推荐
相关产品推荐

