java等比例压缩图片

来源:互联网 发布:知乎周刊合集 编辑:程序博客网 时间:2024/05/17 08:05
public static void resizeImage(String srcImgPath,int width, int height,float quality) throws IOException {          String subfix = "jpg";        subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".")+1,srcImgPath.length());        String prefix=srcImgPath.substring(0,srcImgPath.lastIndexOf("."));                String distImgPath=prefix+"_small."+subfix;        File srcFile = new File(srcImgPath);          Image srcImg = ImageIO.read(srcFile);          int w = srcImg.getWidth(null);        int h = srcImg.getHeight(null);        width=(int)(w*quality);        height=(int)(h*quality);        BufferedImage buffImg = null;         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(Color.WHITE);        graphics.setColor(Color.WHITE);        graphics.fillRect(0, 0, width, height);        graphics.drawImage(srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);           ImageIO.write(buffImg, subfix, new File(distImgPath));      }





调 用方法:

   public static void main(String[] args) {   try {              resizeImage("D:\\222.jpg",400,250,0.5f);         } catch (IOException e) {          }  }



0 0
原创粉丝点击