EasyExcel导出压缩图片,判断图片url是否可用
如果有关于EasyExcel导出的其他相关问题,可以查看历史文章,这次主要对EasyExcel导出图片做进一步完善,导出压缩图片
1.压缩图片工具类
/**
* url转成图片并压缩
*/
public static URL downloadAndCompress(String url, float quality) throws IOException {
boolean isExist = checkImageExist(url);
if (!isExist) {
return new URL("");
}
File file = null;
InputStream inputStream = null;
FileOutputStream fos = null;
try {
file = File.createTempFile("image", "jpg");
URL urlFile = new URL(url);
inputStream = urlFile.openStream();
fos = new FileOutputStream(file);
byte[] bytes = new byte[10240];
int bytesRead;
while ((bytesRead = inputStream.read(bytes, 0, 10240)) != -1) {
fos.write(bytes, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != fos) {
fos.close();
}
if (null != inputStream) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 指定压缩图片的方式、参数等
ImageWriter imageWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam imageWriteParam = new JPEGImageWriteParam(null);
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(quality);
imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
ColorModel colorModel = ImageIO.read(file).getColorModel();
imageWriteParam.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(32, 32)));
FileOutputStream out;
if (!file.exists()) {
throw new FileNotFoundException("文件不存在");
} else {
BufferedImage bufferedImage = ImageIO.read(file);
out = new FileOutputStream(file);
imageWriter.reset();
imageWriter.setOutput(ImageIO.createImageOutputStream(out));
imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);
out.flush();
out.close();
}
return file.toURI().toURL();
}
- 判断图片是否可用
/**
* 判断图片数据是否正常
* @param urlString
*/
public static boolean checkImageExist(String urlString) {
URL url;
URLConnection urlConnection;
try {
url = new URL(urlString);
urlConnection = url.openConnection();
int status = ((HttpURLConnection) urlConnection).getResponseCode();
if (status == 200) {
return true;
}
} catch (Exception e1) {
System.out.println("图片不存在!");
}
return false;
}
- 我这里需要返回URL(上面做了类型转换:file.toURI().toURL()),可以根据需要返回对应的类型
// 实体类字段
@ExcelProperty(value = "Event Photo", converter = UrlImageConverter.class)
private URL imagePath;
try {
URL url = ImageUtil.downloadAndCompress(event.getEventPhoto(), 0.1f);
exportExcelVo.setImagePath(url);
} catch (IOException e) {
e.printStackTrace();
}
因为有些时候返回的远程图片url无法正常打开,导致在写入excel时会报异常,所以就先判断url是否可用再写入。