java中的图片按比例缩放功能

jopen 6年前

java中的图片按比例缩放功能

1. 按固定长宽进行缩放

    /*       * 图片缩放,w,h为缩放的目标宽度和高度       * src为源文件目录,dest为缩放后保存目录       */      public static void zoomImage(String src,String dest,int w,int h) throws Exception {                    double wr=0,hr=0;          File srcFile = new File(src);          File destFile = new File(dest);            BufferedImage bufImg = ImageIO.read(srcFile); //读取图片          Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//设置缩放目标图片模板                    wr=w*1.0/bufImg.getWidth();     //获取缩放比例          hr=h*1.0 / bufImg.getHeight();            AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);          Itemp = ato.filter(bufImg, null);          try {              ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile); //写入缩减后的图片          } catch (Exception ex) {              ex.printStackTrace();          }      }

2. 按固定文件大小进行缩放

      /*     * 图片按比率缩放     * size为文件大小     */    public static void zoomImage(String src,String dest,Integer size) throws Exception {        File srcFile = new File(src);        File destFile = new File(dest);                long fileSize = srcFile.length();        if(fileSize < size * 1024)   //文件大于size k时,才进行缩放            return;                Double rate = (size * 1024 * 0.5) / fileSize; // 获取长宽缩放比例                BufferedImage bufImg = ImageIO.read(srcFile);        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);                    AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);        Itemp = ato.filter(bufImg, null);        try {            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);        } catch (Exception ex) {            ex.printStackTrace();        }

来自: http://segmentfault.com/a/1190000004253565