插入图片所用依赖
java"> private static void insertImage(XWPFDocument document, String path) {List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {CTP ctp = paragraph.getCTP();for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) {try {CTBookmark bookmark = ctp.getBookmarkStartArray(dwI);if (!"celue".equalsIgnoreCase(bookmark.getName())) continue;FileInputStream fis = new FileInputStream(new File(path));XWPFRun run = paragraph.createRun();//bus.png为鼠标在word里选择图片时,图片显示的名字,宽度,高度100,100则为像素单元,根据实际需要的大小进行调整即可。run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));} catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {throw new RuntimeException(e);}}}}
上面代码中XWPFDocument documen 用到的依赖在下方
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency>
下面代码对应的依赖在下方
java">XWPFRun run = paragraph.createRun();//bus.png为鼠标在word里选择图片时,图片显示的名字,宽度,高度100,100则为像素单元,根据实际需要的大小进行调整即可。run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency>
剪裁图片所用依赖
java"> public static void main(String[] args) throws IOException {String wordPath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\target1.docx";String destPath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\targetA.docx";String picturePath = convertSuffix(wordPath, ".png");wordToImage(wordPath,"png");FileInputStream fis = new FileInputStream(new File(wordPath));XWPFDocument document = new XWPFDocument(new FileInputStream(new File(wordPath)));insertImage(document, picturePath);}private static void insertImage(XWPFDocument document, String path) {List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {CTP ctp = paragraph.getCTP();for (int dwI = 0; dwI < ctp.sizeOfBookmarkStartArray(); dwI++) {try {CTBookmark bookmark = ctp.getBookmarkStartArray(dwI);if (!"celue".equalsIgnoreCase(bookmark.getName())) continue;FileInputStream fis = new FileInputStream(new File(path));XWPFRun run = paragraph.createRun();//bus.png为鼠标在word里选择图片时,图片显示的名字,宽度,高度100,100则为像素单元,根据实际需要的大小进行调整即可。run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, "target1.jpg", Units.toEMU(400), Units.toEMU(500));} catch (InvalidFormatException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {throw new RuntimeException(e);}}}}
下面是剪裁图片的测试代码,目前剪完后,图片不对,可能是像素点设置的有问题
java"> public static void main(String[] args) throws IOException {String picturePath = "D:\\work\\project\\jar\\wordtopdf-server\\wordtopdfByjdk16\\src\\main\\resources\\targetA..png";BufferedImage bufferedImage = new BufferedImage(793, 1122, BufferedImage.TYPE_INT_RGB);BufferedImage coverImage = ImageUtils.getCoverImage(bufferedImage);File outputfile = new File(picturePath);ImageIO.write(coverImage, "png", outputfile);}
java">package com.hx.utils;import lombok.extern.slf4j.Slf4j;import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;@Slf4j
public class ImageUtils {/*** bufferedImage转InputStream*/public static InputStream bufferedImageToInputStream(BufferedImage image) {ByteArrayOutputStream os = new ByteArrayOutputStream();try {ImageIO.write(image, "png", os);InputStream input = new ByteArrayInputStream(os.toByteArray());return input;} catch (IOException e) {}return null;}/*** 获取图片大小信息*/public static Rectangle getImgRect(BufferedImage image) throws IOException {Iterator readers = ImageIO.getImageReadersByFormatName("png");ImageReader reader = (ImageReader) readers.next();InputStream source = bufferedImageToInputStream(image);ImageInputStream iis = ImageIO.createImageInputStream(source);reader.setInput(iis, true);int imageIndex = 0;return new Rectangle(0, 0, reader.getWidth(imageIndex), reader.getHeight(imageIndex));}/*** 图片裁剪,按指定大小裁剪*/public static BufferedImage imageCut(BufferedImage image, Rectangle rect) throws IOException {// 取得图片读入器Iterator readers = ImageIO.getImageReadersByFormatName("png");System.out.println(readers);ImageReader reader = (ImageReader) readers.next();System.out.println(reader);// 取得图片读入流InputStream source = bufferedImageToInputStream(image);ImageInputStream iis = ImageIO.createImageInputStream(source);reader.setInput(iis, true);// 图片参数ImageReadParam param = reader.getDefaultReadParam();int imageIndex = 0;//Rectangle rect = new Rectangle(0, 0, reader.getWidth(imageIndex), 100);param.setSourceRegion(rect);BufferedImage bi = reader.read(0, param);iis.close();source.close();return bi;}/*** 压缩图片,用于高质量图片质量降低,改变图片大小*/public static BufferedImage compressImage(BufferedImage imageByte, int ppi) {BufferedImage smallImage = null;int width = 0, height = 0;if (imageByte == null)return null;InputStream byteInput = bufferedImageToInputStream(imageByte);try {Image image = ImageIO.read(byteInput);int w = image.getWidth(null);int h = image.getHeight(null);// adjust weight and height to avoid image distortiondouble scale = 0;scale = Math.min((float) ppi / w, (float) ppi / h);width = (int) (w * scale);width -= width % 4;height = (int) (h * scale);if (scale >= (double) 1)return imageByte;BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);buffImg.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);//ByteArrayOutputStream out = new ByteArrayOutputStream();//ImageIO.write(buffImg, "png", out);smallImage = buffImg;} catch (IOException e) {e.printStackTrace();}return smallImage;}/*** 将BufferedImage转换为byte[]* @param image* @return*/public static byte[] bufferedImageToByteArray(BufferedImage image) throws IOException{ByteArrayOutputStream os = new ByteArrayOutputStream();ImageIO.write(image, "png", os);return os.toByteArray();}/* *//*** 将BufferedImage转换pdf*//*public static String imageToPdf(List<BufferedImage> images) throws IOException {log.info("图片转pdf开始===============");String newFile = StrUtil.uuid().replace("-", "") + ".pdf";PdfWriter pdfWriter = new PdfWriter( newFile);PdfDocument pdfDocument = new PdfDocument(pdfWriter);Document document = new Document(pdfDocument);for (BufferedImage image : images) {byte[] data = bufferedImageToByteArray(image);com.itextpdf.layout.element.Image img = new com.itextpdf.layout.element.Image(ImageDataFactory.createPng(data));document.add(img);}document.close();log.info("图片转pdf结束===============");return newFile;}*//*** 获取缩略图图片,用作封面,按长宽比例设备,高度太高裁掉,高度太低补余白*/public static BufferedImage getCoverImage (BufferedImage originalImage) throws IOException {BufferedImage result = null;// 获取图片的长宽int originalWidth = originalImage.getWidth();int originalHeight = originalImage.getHeight();Rectangle rect = ImageUtils.getImgRect(originalImage);if (rect.getHeight() > rect.getWidth()) {rect.setRect(0,0, rect.getWidth(), rect.getWidth() / 1.3);result = ImageUtils.imageCut(originalImage, rect);} else {int newWidth = 800;int newHeight = 600;// 计算缩放比例double scale = Math.min((double) newWidth / originalWidth, (double) newHeight / originalHeight);// 计算调整后的长宽int scaledWidth = (int) (originalWidth * scale);int scaledHeight = (int) (originalHeight * scale);// 创建新的BufferedImage对象,添加余白BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g = resizedImage.createGraphics();Color fillColor = new Color(255, 255, 255); // 白颜色g.setColor(fillColor);g.fillRect(0, 0, newWidth, newHeight);g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);g.dispose();result = resizedImage;}return result;}}