java处理图像库函数,thumbnails图像处理库的使用

前言:

thumbnails是Java一个优秀的图像处理库,可以对图片进行压缩、加水印、裁剪、更改格式等功能。下面为大家介绍使用这个图像处理库。

欢迎大家关注我的公众号,目前正在慢慢地将简书文章搬到公众号,以后简书和公众号文章将同步更新,且简书上的付费文章在公众号上将免费。

04d04afc34fd

java开发那些事

thumbnails的使用:

一、引入依赖:

net.coobird

thumbnailator

0.4.8

二、编写工具类:

说明:这个类第一个方法就是设置上传的图片保存的很路径,比如上传的图片都保存在E:/download/image/目录下;第二个方法就是设置图片保存的子目录,子目录是根据传入的shopId生成的,然后将根目录与子目录拼接起来就是图片的保存路径。

1、PathUtil.java:

public class PathUtil {

// 获取分隔符

private static String separator = System.getProperty("file.separator");

/**

* 图片保存的根目录

* @return

*/

public static String getImgBasePath() {

// 获取操作系统

String os = System.getProperty("os.name");

String basePath = "";

if (os.toLowerCase().startsWith("win")) {

// "/home/xiangze/image/"

basePath = "E:/download/image/";

} else {

basePath = "/home/ftpuser/images/";

}

// 将斜杆替换成分隔符,这样就能保证路径是有效的

basePath = basePath.replace("/", separator);

return basePath;

}

/**

* 图片保存的子目录:

* upload/meilianMall/shop/" + shopId

* @param shopId

* @return

*/

public static String getShopImagePath(long shopId) {

// "/upload/item/shop/"+shopId+"/"

String imagePath = "upload/meilianMall/shop/" + shopId + "/";

return imagePath.replace("/", separator);

}

}

说明:这个类就是用thumbnails来处理图片的,进行压缩,然后加水印,然后把经过了处理的图片保存到dest目标路径下。

2、ImageUtil.java:

public class ImageUtil {

// 设置时间格式

private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

// 生成随机数对象

private static final Random r = new Random();

// 水映图片位置

private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

// 日志相关

private static Logger logger = LoggerFactory.getLogger(ImageUtil.class);

/**

* 对图片进行压缩并加水印

* @param thumbnail

* @param targetAddr 目标路径

* @return

*/

public static String generateThumbnail(File uploadFile,String targetAddr) {

// 传过来的图片可能是重名的,因此系统随机生成不重复名字

String realFileName = getRandomFileName();

// 获取图片扩展名,如jpg,png等

String extension = getFileExtension(uploadFile);

// 目标路径可能不存在,不存在就创建

makeDirPath(targetAddr);

// 获取图片相对路径(目标路径+随机名+扩展名)

String relativeAddr = targetAddr + realFileName + extension;

logger.debug("current relativeAddr is:" + relativeAddr);

// 新生成文件路径(根路径+targetAddr + realFileName + extension)

File dest = new File(PathUtil.getImgBasePath() + relativeAddr);

logger.debug("current complete addr is:" + PathUtil.getImgBasePath() + relativeAddr);

// 创建缩略图并加水映

try {

Thumbnails.of(uploadFile).size(600, 600)

.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark1.jpg")), 0.25f)

.outputQuality(0.8f).toFile(dest);

} catch (IOException e) {

logger.error(e.toString());

e.printStackTrace();

}

return relativeAddr;

}

/**

* 将CommonsMultipartFile转换成File,

* 因为springmvc会自动把前端图片封装成CommonsMultipartFile,

* 上面压缩图片加水映方法可以直接传入CommonsMultipartFile,但是不方便测试,

* 所以上面方法是用的File,然后用这个方法把前端传入的CommonsMultipartFile转为File

* @param cFile

* @return

*/

public static File transferCommonsMultipartFileToFile(CommonsMultipartFile cFile) {

File newFile = new File(cFile.getOriginalFilename());

try {

cFile.transferTo(newFile);

} catch (IllegalStateException e) {

logger.error(e.toString());

e.printStackTrace();

} catch (IOException e) {

logger.error(e.toString());

e.printStackTrace();

}

return newFile;

}

/**

* 生成随机文件名,当前年月日小时分钟秒+五位随机数

* @param args

* @throws IOException

*/

public static String getRandomFileName() {

// 获取随机五位数

int rannum = r.nextInt(89999) + 10000;

// 当前时间

String nowTimeStr = sDateFormat.format(new Date());

return nowTimeStr + rannum;

}

/**

* 获取输入文件流的扩展名

* @param args

* @throws IOException

*/

private static String getFileExtension(File uploadFile) {

String fileName = uploadFile.getName();

return fileName.substring(fileName.lastIndexOf("."));

}

/**

* 目标路径文件夹不存在就创建

* @param args

* @throws IOException

*/

private static void makeDirPath(String targetAddr) {

// 文件全路径

String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;

File dirPath = new File(realFileParentPath);

if (!dirPath.exists()) {

dirPath.mkdirs();

}

}

}

三、测试:

1、把水印图片watermark1.jpg添加到src/test/resources下面。

2、test.java:

@Test

public void testAddShop() {

File shopImg = new File("E:\\download\\image\\windows.jpg");

ImageUtil.generateThumbnail(shopImg, "\\upload\\");

}

可以看到图片已经保存在目标路径下了,并且是随机生成的名字。

04d04afc34fd

图片发自简书App

打开图片可以看到水印已经加上去了,原图大小40kb,操作后的图片大小18k,也经过压缩了。

04d04afc34fd

图片发自简书App

注意:真正在项目中使用的时候,ImageUtils中可以直接传入MultipartFile对象,这里传入File是为了方便测试。

总结:

thumbnails的使用很简单,就是引入依赖,然后就传一个需要进行操作的图片给它,最后用Thumbnails调方法进行各种操作。上面案例可能看起来有点麻烦,其实上面的其他方法都是准备工作,比如设置图片保存的路径、生成随机文件名、创建目标路径的文件夹等。功能也不止上面演示的那两个,需了解老铁们可以自行百度,网上很多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值