1、引入pom依赖
1、1 使用hutool工具包进行excel导入,并解析
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.0.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
2、构建excel对应的模型
2.1、依赖lombok
package com.suy.actuator.model;
import lombok.Data;
@Data
public class ImgBean{
private String name;
private String imgUrl;
}
2.2、excel文件格式
3、图片下载及尺寸修改
package com.suy.actuator.util;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.suy.actuator.model.ImgBean;
import org.junit.jupiter.api.Test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
public class DownloadImg {
@Test
public void downloadImg() {
ExcelReader excelReader = ExcelUtil.getReader(FileUtil.file("imgExcel.xlsx"));
List<ImgBean> imgs = excelReader.readAll(ImgBean.class);
for (ImgBean img : imgs ) {
download(img.getImgUrl(), img.getName());
}
}
public static void download(String urlString, String rename) {
InputStream is = null;
OutputStream os = null;
String oldPath = "D:/oldPath/" + rename + ".jpg";
String newSizePaht = "D:/newPath/" + rename + ".jpg";
try {
URL url = new URL(urlString);
URLConnection con = url.openConnection();
is = con.getInputStream();
byte[] bs = new byte[1024];
int len;
os = new FileOutputStream(new File(oldPath));
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
changeSize(800, 800, oldPath, newSizePaht);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(is, os);
}
}
public static void changeSize(int newWidth, int newHeight, String path, String newSizePath) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(path));
Image bi = ImageIO.read(in);
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
out = new BufferedOutputStream(new FileOutputStream(newSizePath));
ImageIO.write(tag, "jpg", out);
} catch (IOException e) {
e.printStackTrace();
} finally {
close(in, out);
}
}
private static void close(InputStream is, OutputStream os) {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}