Java上传图片,对图片进行等比例缩放,及局部裁剪的工具类代码

2016-11-03 - 992 Views - 0 Goods - Nothing

package com.songliguo.img
import java.util.*;   
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
 

public class FileUploadUtils {
      
    /**
     * 
     * @Title: cutImg 
     * @author: SongLiGuo
     * @Description: TODO(裁剪图片-->返回绝对路径) 
     * @param input
     * @param basepath
     * @param x
     * @param y
     * @param width
     * @param height
     * @return
     * @throws IOException
     * @return: String    返回类型 
     * @date 2016-11-3 下午5:30:20	
     * @throws
     */
    public static String cutImg(String input,String basepath,int x,int y,int width,int height) throws IOException{
        String path2 = basepath+"/"+ConstantUtils.USERFACETEMPPATH;
        String postfix = getPostfix(input);
        String dst = path2 +"/"+UUID.randomUUID().toString()+"."+postfix;
          
        createDir(path2);
        imgCut(basepath+input,dst,postfix,x,y,width,height);
          
        return dst;
    }
      
    /**
     * 
     * @Title: imgCut 
     * @author: SongLiGuo
     * @Description: TODO(裁剪图片) 
     * @param input
     * @param dst
     * @param type
     * @param x
     * @param y
     * @param width
     * @param height
     * @throws IOException
     * @return: void    返回类型 
     * @date 2016-11-3 下午5:29:44	
     * @throws
     */
    public static void imgCut(String input,String dst,String type,int x,int y,int width,int height) throws IOException
     {
            BufferedImage fromimg = ImageIO.read(new File(input));
            ImageFilter cropFilter = new CropImageFilter(x,y,width,height);   
            Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(fromimg.getSource(), cropFilter));
            BufferedImage tag = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);  
              
            Graphics g = tag.getGraphics();   
            g.drawImage(img, 0, 0, null); // 绘制小图   
           g.dispose();   
            // 输出为文件   
           // dir = "d:\temp\cut_image_" + i + "_" + j + ".jpg";   
            File f = new File(dst);   
            ImageIO.write(tag,type, f);  
              
        }
  
  
    /**
     * 
     * @Title: uploadImg 
     * @author: SongLiGuo
     * @Description: TODO(上传头像文件) 
     * @param src
     * @param basepath
     * @param filename
     * @return
     * @throws Exception
     * @return: String    返回类型 
     * @date 2016-11-3 下午5:29:08	
     * @throws
     */
    public static String uploadImg(File src,String basepath,String filename) throws Exception{
        String daypath = DateTools.getYear() + "" + DateTools.getMonth() + "" + DateTools.getMonthWeek();
          
        String temppath = ConstantUtils.BASEUPLOADPATH+"/"+ConstantUtils.ORIGINALIMGPATH+"/" + daypath;
        String thumbnailpath = ConstantUtils.BASEUPLOADPATH+"/"+ConstantUtils.THUMBNAILIMGPATH+"/" + daypath;
          
        String postfix = getPostfix(filename);
        String uuid = UUID.randomUUID().toString();
        String dsttempname = uuid+"."+postfix;
          
        createDir(basepath +"/"+temppath);
        createDir (basepath +"/"+ thumbnailpath);
          
          
        String dstallpath = basepath +"/"+temppath+"/"+dsttempname;
        String dstthumbnailpath = basepath +"/"+thumbnailpath+"/"+dsttempname;
          
        copy(src,new File(dstallpath));
  
        //对上传的文件进行 等比例 裁剪。  按照前段要展现的  height width
        Thumbnail(dstallpath,dstthumbnailpath,350,300,100);
          
        //返回裁剪后的路径 
          
        return thumbnailpath+"/"+dsttempname;
    }
      
    /**
     * 
     * @Title: copy 
     * @author: SongLiGuo
     * @Description: TODO(上传文件) 
     * @param src
     * @param dst
     * @throws Exception
     * @return: void    返回类型 
     * @date 2016-11-3 下午5:28:22	
     * @throws
     */
    public static void copy(File src, File dst) throws Exception {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(src), ConstantUtils.BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst), ConstantUtils.BUFFER_SIZE);
                byte[] buffer = new byte[ConstantUtils.BUFFER_SIZE];
                while (in.read(buffer) > 0) {
                    out.write(buffer);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
      
    /**
     * 
     * @Title: getPostfix 
     * @author: SongLiGuo
     * @Description: TODO(得到文件后缀  jpg) 
     * @param fileName
     * @return
     * @return: String    返回类型 
     * @date 2016-11-3 下午5:28:05	
     * @throws
     */
    public static String getPostfix(String fileName){
        if (fileName.equals(""))
            return "";
        int pos = fileName.lastIndexOf(".");
        if (pos < 0) {
            return fileName.substring(fileName.length() - 3).toLowerCase();
        } else {
            return fileName.substring(pos+1).toLowerCase();
        }
    }
      
    /**
     * 
     * @Title: createDir 
     * @author: SongLiGuo
     * @Description: TODO(创建目录) 
     * @param filePath
     * @return: void    返回类型 
     * @date 2016-11-3 下午5:27:39	
     * @throws
     */
    public static void createDir(String filePath) {
        File myFile = new File(filePath);
        if (!myFile.exists()) {
            if (!myFile.mkdirs())
                System.out.println("创建目录 fail");
            else
                System.out.println("创建目录 success");
        }
        myFile = null;
    }
      
    /**
     * 
     * @Title: Thumbnail 
     * @author: SongLiGuo
     * @Description: TODO(等比例缩放图片) 
     * @param infile
     * @param outfile
     * @param width
     * @param height
     * @param quality
     * @throws IOException
     * @throws InterruptedException
     * @return: void    返回类型 
     * @date 2016-11-3 下午5:27:16	
     * @throws
     */
    public static void Thumbnail(String infile, String outfile, int width, int height, int quality) throws IOException, InterruptedException {
        // save thumbnail image to OUTFILE
        //System.out.println("infile:" + infile);
        BufferedImage thumbImage = null;
        BufferedOutputStream out = null;
        Image image = null;
        image = Toolkit.getDefaultToolkit().createImage(infile);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        mediaTracker.waitForID(0);
        int thumbWidth = width;
        int thumbHeight = height;
        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }
        thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image,0,0, thumbWidth, thumbHeight, null);
        out = new BufferedOutputStream(new FileOutputStream(outfile));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
        quality = Math.max(0, Math.min(quality, 100));
        param.setQuality((float) quality / 100.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
        out.close();
        thumbImage = null;
        out = null;
        image = null;
    }
}


转载请注明原文链接:首页 -> 技术交流 -> JAVA开发 -> Java上传图片,对图片进行等比例缩放,及局部裁剪的工具类代码
  • 支付宝打赏
  • 微信打赏

China.BeiJing

如果说人生是自我编写的程序,那么青春就是其中意味深长的代码