图片处理工具类 util

PathUtil

package util;

public class PathUtil {
    private static String seperator = System.getProperty("file.separator");
    
    // 获取根目录
    public static String getImgBasePath() {
        String os = System.getProperty("os.name");
        String basePath = "";
        if(os.toLowerCase().startsWith("win")) {
            basePath = "D:/image/";
        }
        else {
            basePath = "/home/image/";
        }
        basePath = basePath.replace("/", seperator);
        return basePath;
    }
    
    // 获取存取相对路径
    public static String getShopImagePath(long shopId) {
        String imagePath="/upload/item/shop" + shopId + "/";
        return imagePath.replace("/", seperator);
    }
}

ImageUtil

package util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;

public class ImageUtil {
    private final static  SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMddHHmmss");
    private final static  Random r= new Random();
    
    
    public static void genarateThumbnail(CommonsMultipartFile thumbnail, String targetAddr) {
        // 文件名
        String realFileName = getRandomFileName();
        // 拓展名
        String extension = getFileExtension(thumbnail);
        // 创建目录
        makeDirPath(targetAddr);
        String relativeAddr = targetAddr + realFileName + extension;
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        try {
            Thumbnails.of(thumbnail.getInputStream()).size(200, 200).outputQuality(0.8)
            .toFile(dest);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 创建目标路径所涉及到的目录 
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if(!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }
    /**
     * 获取文件拓展名
     * @param targetAddr
     */
    private static String getFileExtension(CommonsMultipartFile cFile) {
        String originalFileName = cFile.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }
    
    /**
     * 获取随机文件名
     * @return String 文件随机名
     */
    private static String getRandomFileName() {
        int randNum = r.nextInt(89999) + 10000;
        String nowTimestr = sdf.format(new Date());
        return nowTimestr + randNum;
    }

}

 

posted @ 2018-11-23 12:24  Draymonder  阅读(517)  评论(0编辑  收藏  举报