最近在做h5的图片上传 弄了还是挺久的 毕竟第一次弄。最后还是得把图片压缩这功能记录下:
public static InputStream compressImg(FileItemStream fileStream, String suffix){
File file = new File("tmp.jpg");
try {
file.createNewFile();
Image srcFile = ImageIO.read(fileStream.openStream());
int w = srcFile.getWidth(null);
int h = srcFile.getHeight(null);
BufferedImage buffImg = null;
if(suffix.equals("png")){
buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
}else{
buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
}
buffImg.getGraphics().drawImage(srcFile.getScaledInstance(w, h, Image.SCALE_SMOOTH), 0, 0, null);
FileOutputStream out = new FileOutputStream("tmp.jpg");
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(buffImg);
out.close();
// ImageIO.write(buffImg, suffix, file);
return new FileInputStream(file);
} catch (Exception e) {
e.printStackTrace();
}finally {
file.delete();
}
return null;
}