Java 上传图片时按比例压缩图片
一、在文件上传时的代码,判断是否需要进行压缩
if(!filename.endsWith(".xlsx")&&!filename.endsWith(".xls")){
String p="Http://"+domain+":90"+SERVER_IMG_COURSE_CHOOSE_PATH+"/"+filename;
URL url = new URL(p);
/** 对服务器上的临时文件进行处理 */
Image srcFile = ImageIO.read(url);
int w=srcFile.getWidth(null);
int h=srcFile.getWidth(null);
if(w>320||h>180){
InputStream id=ImageZipUtil.zipWidthHeightImageFile(srcFile, filename,p, 320, 180, 0.8f);
if (!ftp.storeFile(new String(filename.getBytes("utf-8"),"iso-8859-1"), id)) {
return result;
}
id.close();
}
}
二、压缩方法
public static InputStream zipWidthHeightImageFile(Image im, String filename,String str,int width, int height, float quality) {
Image srcFile = null;
BufferedImage buffImg = null;
InputStream is=null;
try {
URL url = new URL(str);
/** 对服务器上的临时文件进行处理 */
srcFile = ImageIO.read(url);
// String srcImgPath = newFile.getAbsoluteFile().toString();
// System.out.println(srcImgPath);
String subfix = "jpg";
subfix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
if (subfix.equals("png")) {
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
} else {
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
Graphics2D graphics = buffImg.createGraphics();
graphics.setBackground(new Color(255, 255, 255));
graphics.setColor(new Color(255, 255, 255));
graphics.fillRect(0, 0, width, height);
graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ByteArrayOutputStream os = new ByteArrayOutputStream();
// ImageIO.write(image, "gif", os);
ImageIO.write(buffImg, subfix, os);
is = new ByteArrayInputStream(os.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (srcFile != null) {
srcFile.flush();
}
if (buffImg != null) {
buffImg.flush();
}
}
return is;
}