赞
踩
废话不多说,直接上代码
1. 首先引入图片缩放所需要的依赖(如果不需要对图片进行缩放,则可以省略该步骤)
- <dependency>
- <groupId>org.imgscalr</groupId>
- <artifactId>imgscalr-lib</artifactId>
- <version>4.2</version>
- </dependency>
2. 主方法,网上随便找一张图片,并将生成的.xlsx文件保存到本地路径
- public static void main(String[] args) {
- Workbook workbook = new XSSFWorkbook();
- Sheet sheet = workbook.createSheet("测试");
-
- sheet.createRow(0);
-
- String imageUrl = "图片路径";
- insertImageToSheet(sheet, imageUrl, 0, 0);
-
- saveFile("/Users/xxx/Desktop/test.xlsx", workbook);
- }
3. 将图片插入单元格,其中,旋转图片和缩放图片可根据实际需求自行添加或删除
- /**
- * 将图片插入单元格
- */
- private static void insertImageToSheet(Sheet sheet, String imageUrl, int rowNum, int colNum) {
- //1. 下载图片
- BufferedImage originalImage = downloadImage(imageUrl);
- if (Objects.isNull(originalImage)) {
- return;
- }
-
- //2. 旋转图片
- BufferedImage rotatedImage = rotateImage(originalImage);
-
- //3. 缩放图片
- ScaledImageDataDTO scaledImageData = scaleImage(rotatedImage);
-
- //4.将缩放后的图片转换为bytes
- byte[] imageBytes = processImageToBytes(scaledImageData.getScaledImage());
-
- //5.将图片bytes添加到Excel中
- setIntoSheet(sheet, rowNum, colNum, imageBytes, scaledImageData.getHeight());
- }
- @Data
- @AllArgsConstructor
- public class ScaledImageDataDTO {
-
- private int height;
-
- private BufferedImage scaledImage;
- }
注:缩放图片尺寸可修改desiredWidth值自定义
- /**
- * 下载图片
- */
- private static BufferedImage downloadImage(String imageUrl) {
- try {
- URL url = new URL(imageUrl);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod("GET");
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(5000);
-
- if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
- log.error("【图片下载失败,url:{}, 链接状态码:{}】", imageUrl, connection.getResponseCode());
- return null;
- }
-
- InputStream inputStream = connection.getInputStream();
- BufferedImage image = ImageIO.read(inputStream);
- inputStream.close();
-
- return image;
- } catch (Exception e) {
- log.error("【图片下载失败,url:{}, 错误信息:{}】", imageUrl, e);
- return null;
- }
- }
-
- /**
- * 旋转图片
- */
- private static BufferedImage rotateImage(BufferedImage targetImage) {
- int w = targetImage.getWidth();
- int h = targetImage.getHeight();
-
- BufferedImage rotatedImage = new BufferedImage(h, w, targetImage.getType());
- Graphics2D g2d = rotatedImage.createGraphics();
-
- AffineTransform at = new AffineTransform();
- at.translate(h / 2.0, w / 2.0);
- at.rotate(Math.toRadians(270),0, 0);
- at.translate(-w / 2.0, -h / 2.0);
- g2d.drawRenderedImage(targetImage, at);
- g2d.dispose();
-
- return rotatedImage;
- }
-
- /**
- * 缩放图片
- */
- private static ScaledImageDataDTO scaleImage(BufferedImage targetImage) {
- int desiredWidth = 170; // 图片宽度
- double aspectRatio = (double) targetImage.getHeight() / targetImage.getWidth();
- int desiredHeight = (int) (desiredWidth * aspectRatio); // 保持纵横比
-
- BufferedImage scaledImage = Scalr.resize(targetImage, Scalr.Method.QUALITY, desiredWidth, desiredHeight);
- return new ScaledImageDataDTO(desiredHeight, scaledImage);
- }
-
- /**
- * 图片转bytes
- */
- private static byte[] processImageToBytes(BufferedImage targetImage) {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- try {
- ImageIO.write(targetImage, "png", stream);
- return stream.toByteArray();
- } catch (IOException e) {
- log.error("【图片转bytes异常,错误信息:】", e);
- return new byte[0];
- }
- }
-
- /**
- * 将图片bytes添加到Excel中
- */
- private static void setIntoSheet(Sheet sheet, int rowNum, int colNum, byte[] imageBytes, int imageHeight) {
- int pictureIdx = sheet.getWorkbook().addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
- CreationHelper helper = sheet.getWorkbook().getCreationHelper();
- Drawing<?> drawing = sheet.createDrawingPatriarch();
- ClientAnchor anchor = helper.createClientAnchor();
- anchor.setCol1(colNum);
- anchor.setRow1(rowNum);
- Picture pict = drawing.createPicture(anchor, pictureIdx);
-
- // 设置行高度以匹配图片高度
- Row row = sheet.getRow(rowNum);
- row.setHeightInPoints((float) (imageHeight * 0.75));
-
- pict.resize();
- }
代码亲测有效,如有疑问欢迎留言噢~
Dependent on GPT4.0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。