一、在文件上传时的代码,判断是否需要进行压缩

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;
}

相关文章:

  • 2021-12-23
  • 2021-12-31
  • 2022-01-16
  • 2021-11-23
  • 2021-07-20
  • 2021-12-10
  • 2021-11-22
猜你喜欢
  • 2022-12-23
  • 2021-11-23
  • 2021-11-23
  • 2022-02-18
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案