图片处理工具类 util
Posted draymonder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片处理工具类 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; } }
以上是关于图片处理工具类 util的主要内容,如果未能解决你的问题,请参考以下文章
Java常用工具类---image图片处理工具类Json工具类