序
这里展示一下如何对图片进行压缩和resize。
压缩
1public static boolean compress(String src,String to, float quality) { 2 boolean rs = true; 3 4 // Build param 5 JPEGEncodeParam param = null; 6 7 // Build encoder 8 File destination = new File(to); 9 FileOutputStream os = null; 10 try { 11 BufferedImage image = ImageIO.read(new File(src)); 12 param = JPEGCodec.getDefaultJPEGEncodeParam(image); 13 param.setQuality(quality, false); 14 15 os = FileUtils.openOutputStream(destination); 16 JPEGImageEncoder encoder; 17 if (param != null) { 18 encoder = JPEGCodec.createJPEGEncoder(os, param); 19 } else { 20 return false; 21 } 22 encoder.encode(image); 23 } catch(Exception e){ 24 e.printStackTrace(); 25 rs = false; 26 }finally { 27 IOUtils.closeQuietly(os); 28 } 29 return rs; 30 }
resize
1public static boolean resize(String src,String to,int newWidth,int newHeight) { 2 try { 3 File srcFile = new File(src); 4 File toFile = new File(to); 5 BufferedImage img = ImageIO.read(srcFile); 6 int w = img.getWidth(); 7 int h = img.getHeight(); 8 BufferedImage dimg = new BufferedImage(newWidth, newHeight, img.getType()); 9 Graphics2D g = dimg.createGraphics(); 10 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 11 g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null); 12 g.dispose(); 13 ImageIO.write(dimg, "jpg", toFile); 14 } catch (Exception e) { 15 e.printStackTrace(); 16 return false; 17 } 18 return true; 19 }