zoukankan      html  css  js  c++  java
  • java处理图片按比例缩放功能

    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时,才进行缩放,注意: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();
    		}
    	}
    
    
  • 相关阅读:
    [AT2064] [agc005_f] Many Easy Problems
    [AT2304] [agc010_c] Cleaning
    [AT2172] [agc007_e] Shik and Travel
    [AT2148] [arc063_c] Integers on a Tree
    [AT2363] [agc012_c] Tautonym Puzzle
    未能从程序集“netstandard, Version=2.0.0.0......”中加载类型“...”。
    Android Studio设置国内镜像代理
    新建一个浏览器APP
    Android Studio在Make Project时下载Grandle特别慢
    用JS添加和删除class类名
  • 原文地址:https://www.cnblogs.com/a8167270/p/5103395.html
Copyright © 2011-2022 走看看