1. 程式人生 > >圖片處理工具類 util

圖片處理工具類 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; } }