1、如果在springMvc中,会自带生成MultipartFile文件,将MultipartFile转化为File
1 MultipartFile file1 = file; 2 CommonsMultipartFile cf= (CommonsMultipartFile)file1; 3 DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 4 File f = fi.getStoreLocation();
2、转化为image类,并获取一些必须的数值
1 private static Image img; 2 private static float width; 3 private static float height; 4 5 img = ImageIO.read(f); // 构造Image对象 6 width = Float.parseFloat(String.valueOf(img.getWidth(null))); // 得到源图宽 7 height = Float.parseFloat(String.valueOf(img.getHeight(null))); // 得到源图长 8 9 System.out.println("输入的图片大小:"+f.length()/1024+"kb");
3、压缩图片
1 //判断文件是否能转化成image类 2 if(width!=-1){ 3 //当前例子是等比例缩放到宽为320px 4 //缩放比例 5 Float s=width/320; 6 //要缩放的宽 7 Integer w=(int) (width/s); 8 //要缩放的高 9 Integer h=(int) (height/s); 10 11 //创建一个模板 12 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB); 13 //在模板上绘制缩小后的图 14 image.getGraphics().drawImage(img, 0, 0, w, h, null); 15 }
4、将生成的图片转化为InputStream
ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "gif", os); InputStream is = new ByteArrayInputStream(os.toByteArray());