直接看代码吧,主要逻辑吧excel的图片拿到 压缩上传获取url文章来源地址https://www.toymoban.com/news/detail-651606.html
// 将文件转成XSSFWorkbook工作簿
XSSFWorkbook wb = new XSSFWorkbook(uploadFile);
// 获取工作薄中第一个excel表格
XSSFSheet sheet = wb.getSheetAt(0);
// 核心:::获取excel表格中所有图片,处理图片上传到oss key:行号-列号
Map<String, List<String>> picturesMap = getPictures(sheet);
public Map<String, List<String>> getPictures(XSSFSheet xssfSheet) throws IOException {
Map<String, List<String>> maps = new LinkedHashMap<>();
List<XSSFShape> list = xssfSheet.getDrawingPatriarch().getShapes();
for (int i = 0; i < list.size(); i++) {
XSSFPicture picture = (XSSFPicture) list.get(i);
// 行号-列号
XSSFClientAnchor xssfClientAnchor = (XSSFClientAnchor) picture.getAnchor();
// 获取图片
XSSFPictureData pdata = picture.getPictureData();
byte[] data = pdata.getData();
InputStream inputStream = new ByteArrayInputStream(data);
byte[] scalePicLater = scalePics(inputStream,0.5,0.5);
String url = ossFactory.build().upload(new ByteArrayInputStream(scalePicLater), IdUtil.objectId() + ".jpg");
inputStream.close();
// 行号-列号
String key = xssfClientAnchor.getRow1() - 1 + "-" + xssfClientAnchor.getCol1();
if (maps.containsKey(key)) {
List<String> strUrl = maps.get(key);
strUrl.add(url);
maps.put(key, strUrl);
} else {
List<String> strUrl = new ArrayList<>();
strUrl.add(url);
maps.put(key, strUrl);
}
}
return maps;
}
public static byte[] scalePics(InputStream inputStream, double accuracy,double scale) throws IOException {
// 压缩图片并保存到临时文件中
File tempFile = File.createTempFile("thumbnail", ".jpg");
Thumbnails.of(inputStream)
.scale(scale)
.outputQuality(accuracy)
.toFile(tempFile);
// 读取临时文件的字节流设置到输出流中
InputStream tempInputStream = new FileInputStream(tempFile);
byte[] buffer = new byte[tempInputStream.available()];
tempInputStream.read(buffer);
tempInputStream.close();
// 删除临时文件
tempFile.delete();
// 下载到本地,
// BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\Code\\upload\\1.jpg"));
// bos.write(buffer);
// bos.close();
return buffer;
}
文章来源:https://www.toymoban.com/news/detail-651606.html
到了这里,关于java导入excel图片处理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!