java實(shí)現(xiàn)上傳圖片并壓縮圖片大小功能
Thumbnailator 是一個(gè)優(yōu)秀的圖片處理的Google開源Java類庫。處理效果遠(yuǎn)比Java API的好。從API提供現(xiàn)有的圖像文件和圖像對(duì)象的類中簡(jiǎn)化了處理過程,兩三行代碼就能夠從現(xiàn)有圖片生成處理后的圖片,且允許微調(diào)圖片的生成方式,同時(shí)保持了需要寫入的最低限度的代碼量。還支持對(duì)一個(gè)目錄的所有圖片進(jìn)行批量處理操作。
支持的處理操作:圖片縮放,區(qū)域裁剪,水印,旋轉(zhuǎn),保持比例。
另外值得一提的是,Thumbnailator至今仍不斷更新,怎么樣,感覺很有保障吧!
下面我們介紹下如何使用Thumbnailator
使用介紹地址:
利用Thumbnailator輕松實(shí)現(xiàn)圖片縮放、旋轉(zhuǎn)與加水印
縮略圖壓縮文件jar包
<!-- 圖片縮略圖 --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency>
按指定大小把圖片進(jìn)行縮放(會(huì)遵循原圖高寬比例)
//按指定大小把圖片進(jìn)行縮和放(會(huì)遵循原圖高寬比例) //此處把圖片壓成400×500的縮略圖 Thumbnails.of(fromPic).size(400,500).toFile(toPic); //變?yōu)?00*300,遵循原圖比例縮或放到400*某個(gè)高度
按照指定比例進(jìn)行縮小和放大
//按照比例進(jìn)行縮小和放大 Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例縮小 Thumbnails.of(fromPic).scale(2f);//按比例放大
圖片尺寸不變,壓縮圖片文件大小
//圖片尺寸不變,壓縮圖片文件大小outputQuality實(shí)現(xiàn),參數(shù)1為最高質(zhì)量 Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);
我這里只使用了 圖片尺寸不變,壓縮文件大小 源碼
/**
*
* @Description:保存圖片并且生成縮略圖
* @param imageFile 圖片文件
* @param request 請(qǐng)求對(duì)象
* @param uploadPath 上傳目錄
* @return
*/
public static BaseResult uploadFileAndCreateThumbnail(MultipartFile imageFile,HttpServletRequest request,String uploadPath) {
if(imageFile == null ){
return new BaseResult(false, "imageFile不能為空");
}
if (imageFile.getSize() >= 10*1024*1024)
{
return new BaseResult(false, "文件不能大于10M");
}
String uuid = UUID.randomUUID().toString();
String fileDirectory = CommonDateUtils.date2string(new Date(), CommonDateUtils.YYYY_MM_DD);
//拼接后臺(tái)文件名稱
String pathName = fileDirectory + File.separator + uuid + "."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//構(gòu)建保存文件路勁
//2016-5-6 yangkang 修改上傳路徑為服務(wù)器上
String realPath = request.getServletContext().getRealPath("uploadPath");
//獲取服務(wù)器絕對(duì)路徑 linux 服務(wù)器地址 獲取當(dāng)前使用的配置文件配置
//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()) {
//創(chuàng)建文件
file.getParentFile().mkdirs();
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = imageFile.getInputStream();
fileOutputStream = new FileOutputStream(file);
//寫出文件
//2016-05-12 yangkang 改為增加緩存
// IOUtils.copy(inputStream, fileOutputStream);
byte[] buffer = new byte[2048];
IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
buffer = null;
} catch (IOException e) {
filePathName = null;
return new BaseResult(false, "操作失敗", e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
return new BaseResult(false, "操作失敗", e.getMessage());
}
}
// String fileId = FastDFSClient.uploadFile(file, filePathName);
/**
* 縮略圖begin
*/
//拼接后臺(tái)文件名稱
String thumbnailPathName = fileDirectory + File.separator + uuid + "small."
+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
//added by yangkang 2016-3-30 去掉后綴中包含的.png字符串
if(thumbnailPathName.contains(".png")){
thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
}
long size = imageFile.getSize();
double scale = 1.0d ;
if(size >= 200*1024){
if(size > 0){
scale = (200*1024f) / size ;
}
}
//拼接文件路勁
String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
try {
//added by chenshun 2016-3-22 注釋掉之前長(zhǎng)寬的方式,改用大小
// Thumbnails.of(filePathName).size(width, height).toFile(thumbnailFilePathName);
if(size < 200*1024){
Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
}else{
Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
}
} catch (Exception e1) {
return new BaseResult(false, "操作失敗", e1.getMessage());
}
/**
* 縮略圖end
*/
Map<String, Object> map = new HashMap<String, Object>();
//原圖地址
map.put("originalUrl", pathName);
//縮略圖地址
map.put("thumbnailUrl", thumbnailPathName);
return new BaseResult(true, "操作成功", map);
}
獲取當(dāng)前使用的配置文件信息
/**
* 根據(jù)key從gzt.properties配置文件獲取配置信息
* @param key 鍵值
* @return
*/
public String getSysPro(String key){
return getSysPro(key, null);
}
/**
* 根據(jù)key從gzt.properties配置文件獲取配置信息
* @param key 鍵值
* @param defaultValue 默認(rèn)值
* @return
*/
public String getSysPro(String key,String defaultValue){
return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);
}
例:
//獲取服務(wù)器絕對(duì)路徑 linux 服務(wù)器地址
String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");
PropertiesUtil 類
package com.xyz.imageserver.common.properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @ClassName PropertiesUtil.java
* @Description 系統(tǒng)配置工具類
* @author caijy
* @date 2015年6月9日 上午10:50:38
* @version 1.0.0
*/
public class PropertiesUtil {
private Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
private ConcurrentHashMap<String, Properties> proMap;
private PropertiesUtil() {
proMap = new ConcurrentHashMap<String, Properties>();
}
private static PropertiesUtil instance = new PropertiesUtil();
/**
* 獲取單例對(duì)象
* @return
*/
public static PropertiesUtil getInstance()
{
return instance;
}
/**
* 根據(jù)key從gzt.properties配置文件獲取配置信息
* @param key 鍵值
* @return
*/
public String getSysPro(String key){
return getSysPro(key, null);
}
/**
* 根據(jù)key從gzt.properties配置文件獲取配置信息
* @param key 鍵值
* @param defaultValue 默認(rèn)值
* @return
*/
public String getSysPro(String key,String defaultValue){
return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);
}
/**
* 從配置文件中獲取對(duì)應(yīng)key值
* @param fileName 配置文件名
* @param key key值
* @param defaultValue 默認(rèn)值
* @return
*/
public String getValue(String fileName,String key,String defaultValue){
String val = null;
Properties properties = proMap.get(fileName);
if(properties == null){
InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
try {
properties = new Properties();
properties.load(new InputStreamReader(inputStream,"UTF-8"));
proMap.put(fileName, properties);
val = properties.getProperty(key,defaultValue);
} catch (IOException e) {
logger.error("getValue",e);
}finally{
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e1) {
logger.error(e1.toString());
}
}
}else{
val = properties.getProperty(key,defaultValue);
}
return val;
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Cloud Gateway全局通用異常處理的實(shí)現(xiàn)
這篇文章主要介紹了Spring Cloud Gateway全局通用異常處理的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Java靜態(tài)和非靜態(tài)成員變量初始化過程解析
這篇文章主要介紹了Java靜態(tài)和非靜態(tài)成員變量初始化過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
springboot jasypt2.x與jasypt3.x的使用方式
在軟件開發(fā)中,將配置文件中的敏感信息(如數(shù)據(jù)庫密碼)進(jìn)行加密是保障安全的有效手段,jasypt框架提供了這一功能,支持通過加密工具類或命令行工具生成密文,并通過修改配置文件和啟動(dòng)參數(shù)的方式使用密文和密鑰,這樣即便配置文件被泄露2024-09-09
使用Spring自定義注解實(shí)現(xiàn)任務(wù)路由的方法
本篇文章主要介紹了使用Spring自定義注解實(shí)現(xiàn)任務(wù)路由的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
@Autowired注解注入的xxxMapper報(bào)錯(cuò)問題及解決
這篇文章主要介紹了@Autowired注解注入的xxxMapper報(bào)錯(cuò)問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
解析Spring Boot 如何讓你的 bean 在其他 bean&n
在 SpringBoot 中如何讓自己的某個(gè)指定的 Bean 在其他 Bean 前完成被 Spring 加載?我聽到這個(gè)問題的第一反應(yīng)是,為什么會(huì)有這樣奇怪的需求?下面小編給大家分析下Spring Boot 如何讓你的 bean 在其他 bean 之前完成加載 ,感興趣的朋友一起看看吧2024-01-01
Redis結(jié)合AOP與自定義注解實(shí)現(xiàn)分布式緩存流程詳解
項(xiàng)目中如果查詢數(shù)據(jù)是直接到MySQL數(shù)據(jù)庫中查詢的話,會(huì)查磁盤走IO,效率會(huì)比較低,所以現(xiàn)在一般項(xiàng)目中都會(huì)使用緩存,目的就是提高查詢數(shù)據(jù)的速度,將數(shù)據(jù)存入緩存中,也就是內(nèi)存中,這樣查詢效率大大提高2022-11-11
使用Feign實(shí)現(xiàn)微服務(wù)間文件傳輸
這篇文章主要為大家詳細(xì)介紹了使用Feign實(shí)現(xiàn)微服務(wù)間文件傳輸,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04
Springboot集成RabbitMQ報(bào)錯(cuò)及解決
這篇文章主要介紹了Springboot集成RabbitMQ報(bào)錯(cuò)及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07

