<span style="font-size:18px;"> 最近项目中有个需求,需要批量对图片服务器上的图片进行压缩,并将压缩后的文件上传到图片服务器上,对图片的压缩处理方面决定采用ImageIO来进行。</span>
javax.imageio.ImageIO,提供了常用的图片I/O操作,包括图片的读取,图片的解析,图片的绘制等,更多详细功能可阅读其源码,参考代码如下:
ByteArrayOutputStream bs = null;<span style="font-family: Arial, Helvetica, sans-serif;">//加载图片</span>
ImageOutputStream imOut = null;
InputStream inputStream = null;
try {
URL url = new URL(imgUrl);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(url);//此处使用URL来获取图片服务器上的图片信息
} catch (Exception e1) {
//在获取图片的时候有小部分图片出现<span style="font-family: FangSong_GB2312;">Unsupported Image Type异常,暂时没做处理</span>
//解决Unsupported Image Type的异常
if (e1.getMessage().contains("Unsupported Image Type")) {
//todo 图片的格式异常,需要做下处理
throw e1;
} else {
throw e1;
}
}
int picWidth = bufferedImage.getWidth(); //得到图片的宽度
int picHeight = bufferedImage.getHeight(); //得到图片的高度
//2、设置缩放后的宽和高(如果宽高都小于等于800像素则不进行操作)
if (picWidth <= maxSize && picHeight <= maxSize) {
//如果都小于800则不需要切图
//不需要操作
}
//分两种情况,宽大于高||宽小于高
double scale = 0D;//设定压缩比例
if (picWidth >= picHeight) { //1、宽>=高
scale = picWidth / maxSize;
}
if (picWidth < picHeight) { //2、宽<高
scale = picHeight / maxSize;
}
int newPicWidth = 0;//新图片的宽
newPicWidth = new Double(picWidth / scale).intValue();
int newPicHeight = 0;//新图片的高
newPicHeight = new Double(picHeight / scale).intValue();
//3、重新绘制压缩图
Image image = bufferedImage.getScaledInstance(newPicWidth, newPicHeight, Image.SCALE_SMOOTH);
BufferedImage outputImage =
new BufferedImage(newPicWidth, newPicHeight, BufferedImage.TYPE_INT_RGB);
Graphics graphics = outputImage.getGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
//4、从重新绘制的图片中获取inputstream,并上传到fastDFS服务器上
String filePrefix = imgUrl.substring(imgUrl.lastIndexOf(".") + 1);
bs = new ByteArrayOutputStream();
imOut = ImageIO.createImageOutputStream(bs);
ImageIO.write(outputImage, filePrefix, imOut);
inputStream = new ByteArrayInputStream(bs.toByteArray());
//对压缩后的图片上传fastDFS服务器(此处可自行进行操作)
fdfsClientFactory.getFastdfsClient()
.upload("", inputStream, imOut.length(), filePrefix, null);
} catch (Exception e1) {
logger.error("压缩图片出现问题,压缩的图片为{}",imgUrl);
logger.error("",e1);
} finally {
try {
if (bs != null) {
bs.close();
}
if (imOut != null) {
imOut.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (Exception e2) {
logger.error("关闭stream流失败",e2);
}
}