Thumbnails是Google公司开源的图片处理工具

一、将Thumbnails引入到maven工程

<dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version>
</dependency>

二、关键代码

String filePathName = "需要压缩的图片根路径";
String thumbnailFilePathName = "压缩之后的图片路径";
double scale = 1d;//图片缩小倍数(0~1),1代表保持原有的大小
double quality = 1d;//压缩的质量,1代表保持原有的大小(默认1)

Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);Thumbnails.of(filePathName).size(400,500).toFile(thumbnailFilePathName);//变为400*500,遵循原图比例缩或放到400*某个高度

三、Spring-boot的例子

package com.example.atlogging.controller;import com.alibaba.fastjson.JSONObject;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;@RestController
@RequestMapping(path = "/thumb", produces = "application/json;charset=UTF-8")
public class TestThumbnails {/*** @Description:保存图片并且生成缩略图* @param imageFile 图片文件* @param request 请求对象* @param uploadPath 上传目录* @return*/private static Logger log = LoggerFactory.getLogger(TestThumbnails.class);@RequestMapping("/up")public String testThumb(MultipartFile imageFile, HttpServletRequest request) {String res = this.uploadFileAndCreateThumbnail(imageFile, request, "");return res;}public static String uploadFileAndCreateThumbnail(MultipartFile imageFile, HttpServletRequest request, String uploadPath) {JSONObject result = new JSONObject();int maxWidth = 1200;//压缩之后的图片最大宽度if (imageFile == null) {result.put("msg", "imageFile不能为空");return result.toJSONString();}if (imageFile.getSize() >= 10 * 1024 * 1024) {result.put("msg", "文件不能大于10M");return result.toJSONString();}String uuid = UUID.randomUUID().toString();String fileDirectory = new SimpleDateFormat("yyyyMMdd").format(new Date());//设置日期格式//拼接后台文件名称String pathName = fileDirectory + File.separator + uuid + "."+ FilenameUtils.getExtension(imageFile.getOriginalFilename());//构建保存文件路径//修改上传路径为服务器上String realPath = "F:/桌面temp/ys";//request.getServletContext().getRealPath("uploadPath");//获取服务器绝对路径 linux 服务器地址  获取当前使用的配置文件配置//String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");//拼接文件路径String filePathName = realPath + File.separator + pathName;log.info("图片上传路径:" + filePathName);//判断文件保存是否存在File file = new File(filePathName);if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {//创建文件
            file.getParentFile().mkdirs();}InputStream inputStream = null;FileOutputStream fileOutputStream = null;try {inputStream = imageFile.getInputStream();fileOutputStream = new FileOutputStream(file);//写出文件
//            IOUtils.copy(inputStream, fileOutputStream);byte[] buffer = new byte[2048];IOUtils.copyLarge(inputStream, fileOutputStream, buffer);buffer = null;} catch (IOException e) {filePathName = null;result.put("msg", "操作失败");return result.toJSONString();} finally {try {if (inputStream != null) {inputStream.close();}if (fileOutputStream != null) {fileOutputStream.flush();fileOutputStream.close();}} catch (IOException e) {filePathName = null;result.put("msg", "操作失败");return result.toJSONString();}}//拼接后台文件名称String thumbnailPathName = fileDirectory + File.separator + uuid + "small."+ FilenameUtils.getExtension(imageFile.getOriginalFilename());if (thumbnailPathName.contains(".png")) {thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");}long size = imageFile.getSize();double scale = 1d;double quality = 1d;if (size >= 200 * 1024) {//当图片超过200kb的时候进行压缩处理if (size > 0) {quality = (200 * 1024f) / size;}}//图片信息double width = 0;double height = 0;try {BufferedImage bufferedImage = ImageIO.read(imageFile.getInputStream()); //获取图片流if (bufferedImage == null) {// 证明上传的文件不是图片,获取图片流失败,不进行下面的操作
            }width = bufferedImage.getWidth(); // 通过图片流获取图片宽度height = bufferedImage.getHeight(); // 通过图片流获取图片高度// 省略逻辑判断} catch (Exception e) {// 省略异常操作
        }System.out.println(width);while (width * scale > maxWidth) {//处理图片像素宽度(当像素大于1200时进行图片等比缩放宽度)scale -= 0.1;}//拼接文件路径String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;System.out.println(scale);System.out.println(quality);System.out.println((int) width * scale);/*if(true){return result.toJSONString();}*/try {//注释掉之前长宽的方式,改用大小
//          Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);if (size < 200 * 1024) {Thumbnails.of(filePathName).scale(scale).outputFormat("jpg").toFile(thumbnailFilePathName);} else {Thumbnails.of(filePathName).scale(scale).outputQuality(quality).outputFormat("jpg").toFile(thumbnailFilePathName);//(thumbnailFilePathName + "l.");
            }} catch (Exception e1) {result.put("msg", "操作失败");return result.toJSONString();}/*** 缩略图end*///原图地址result.put("originalUrl", pathName);//缩略图地址result.put("thumbnailUrl", thumbnailPathName);//缩略图地址result.put("msg", "操作成功");result.put("status", 200);return result.toJSONString();}
}

  

转载于:https://www.cnblogs.com/zhizou/p/11244015.html

使用Thumbnails工具对图片进行缩放,压缩相关推荐

  1. php扇形分布图,PHP制作3D扇形统计图以及对图片进行缩放操作实例

    这篇文章主要介绍了PHP制作3D扇形统计图以及对图片进行缩放操作实例,需要的朋友可以参考下 1.利用php gd库的函数绘制3D扇形统计图 header("content-type" ...

  2. html 鼠标移动到图片时,对图片进行缩放

    之前在研究如何在鼠标放置于图片上时,对图片进行缩放,鼠标离开后恢复图片大小. 一开始用的是修改图片的width和height值,我用bootstrap的栅栏放置的图片,结果出现了排版错误,效果很不理想 ...

  3. WinMount是一款国产免费且功能强大Windows小工具,具备压缩解压和虚拟光驱(CD/DVD)的双重功能...

    http://cn.winmount.com/index.html WinMount是一款国产免费且功能强大Windows小工具,具备压缩解压和虚拟光驱(CD/DVD)的双重功能.最大特色在于压缩包虚 ...

  4. C#对图片进行缩放变换

    C#对图片进行缩放变换 using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...

  5. [文件上传工具类] Thumbnails之上传图片后压缩等处理

    目录 1. Thumbnails简介 2. 导入依赖 3. 图片压缩工具类代码 4. 参数介绍 1. Thumbnails简介 图像处理API,可以实现图像常用操作(图片信息.扩大.缩小.压缩等) 2 ...

  6. 使用react-cropper结合图片压缩方法对图片进行裁剪压缩处理

    最近项目要使用图片裁剪上传,因为项目采用的是react+antd,所以第一时间想到的是ImgCrop插件,但是这不满足项目需求,项目要求的是能够缩放裁剪框,最后确定了采用react-cropper来实 ...

  7. 【PC工具】文件压缩解压工具winrar解压缩装机必备软件,winRAR5.70免费无广告

    微信关注 "DLGG创客DIY" 设为"星标",重磅干货,第一时间送达. 今天分享一个常用的压缩解压工具winrar. 为啥要搞这个无广告版呢(废话),总之网上 ...

  8. 【PC工具】图片压缩哪家强!tinyPNG图片压缩工具

    不算云服务软件,可能大家最喜欢的应该就是在线(网页)软件了,网页软件功能强大,使用方便,打开浏览器就能用,可以免去软件安装的耗时,也能避免硬盘空间的占用.今天给大家分享一个在线的图片压缩网站:http ...

  9. Linux 命令之 tar 命令-打包和备份的归档工具(附压缩/解压工具)

    文章目录 一.命令介绍 二.命令语法 三.常用选项 四.命令示例 (一)对指定的目录进行打包(即备份归档),不压缩 (二)对指定目录下的内容(不含目录本身)进行打包(即备份归档),不压缩 (三)通过通 ...

最新文章

  1. Android用户界面开发(2):ListView
  2. MySQL中文全文检索
  3. 给div命名,使逻辑更加清晰
  4. 【Flink】ValidationException: Comparison is only supported for numeric types and comparable types
  5. Jenkins学习总结(3)——Jenkins+Maven+Git搭建持续集成和自动化部署的
  6. python工资一般多少p-预测python数据分析师的工资
  7. 【Robot Framework】字符串判断,if语句多执行条件,多执行语句
  8. ui设计移动端字体适配_手机端页面UI设计尺寸和字体大小规范
  9. 安装 Maxwell
  10. 文件系统性能测试工具iozone
  11. 计算机的好与坏作文,电脑“坏”了的作文
  12. 2020年中华人民共和国行政区划代码
  13. html 转盘抽奖开发,html 大转盘抽奖
  14. jemter ramp-up
  15. windows IIS Web服务器 发布网站
  16. 《SolidWorks 2014中文版完全自学手册》——1.2 SolidWorks 2014简介
  17. 在腾讯云搭建代理服务器的全部过程
  18. 立夏游雪上,赏奇花,正当时:天台九遮山
  19. 玉米社:竞价推广关键词出价原则,注意这几点!
  20. 手机联系人姓名或号码过长无法导入到SIM卡

热门文章

  1. 基于Mahout实现协同过滤推荐算法的电影推荐系统
  2. 为什么在ROS中启动小乌龟后,无法用键盘控制?
  3. 高通平台MSM8916 LCM ID读取方法
  4. web渗透测试培训,如何做信息收集?
  5. Remind-You Part3. Python-Sqlite记录数据
  6. 哪家的微信三级分销系统功能比较好
  7. 塔望3W消费战略全案|小靳师傅:地方美食如何乘上新速食时代快车
  8. 漏洞深度分析|CVE-2022-1471 SnakeYaml 命令执行漏洞
  9. Gabor滤波器学习 综合多篇关于Gabor滤波器的博客总结
  10. 机房信息管理系统总结