java實現上傳圖片並壓縮圖片大小功能

縮略圖壓縮文件jar包html

<!-- 圖片縮略圖 -->
 <dependency>
 <groupId>net.coobird</groupId>
 <artifactId>thumbnailator</artifactId>
 <version>0.4.8</version>
</dependency>

 按指定大小把圖片進行縮放(會遵循原圖高寬比例)java

//按指定大小把圖片進行縮和放(會遵循原圖高寬比例) 
 //此處把圖片壓成400×500的縮略圖
Thumbnails.of(fromPic).size(400,500).toFile(toPic);
 
//變爲400*300,遵循原圖比例縮或放到400*某個高度

按照指定比例進行縮小和放大linux

//按照比例進行縮小和放大
Thumbnails.of(fromPic).scale(0.2f).toFile(toPic);//按比例縮小
Thumbnails.of(fromPic).scale(2f);//按比例放大

  圖片尺寸不變,壓縮圖片文件大小spring

//圖片尺寸不變,壓縮圖片文件大小outputQuality實現,參數1爲最高質量
Thumbnails.of(fromPic).scale(1f).outputQuality(0.25f).toFile(toPic);

  這裏只使用了 圖片尺寸不變,壓縮文件大小 源碼緩存

/**
 * 
 * @Description:保存圖片而且生成縮略圖
 * @param imageFile 圖片文件
 * @param request 請求對象
 * @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);
  
 //拼接後臺文件名稱
 String pathName = fileDirectory + File.separator + uuid + "."
  + FilenameUtils.getExtension(imageFile.getOriginalFilename());
 //構建保存文件路勁
 //2016-5-6 yangkang 修改上傳路徑爲服務器上 
 String realPath = 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);
 //寫出文件
 //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
 */
  
 //拼接後臺文件名稱
 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 註釋掉以前長寬的方式,改用大小
// 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);
 }

獲取當前使用的配置文件信息服務器

/**
* 根據key從gzt.properties配置文件獲取配置信息 
* @param key 鍵值
* @return
*/
public String getSysPro(String key){
return getSysPro(key, null);
}
/**
* 根據key從gzt.properties配置文件獲取配置信息 
* @param key 鍵值
* @param defaultValue 默認值
* @return
*/
public String getSysPro(String key,String defaultValue){
return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);
}

例:dom

//獲取服務器絕對路徑 linux 服務器地址 
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 系統配置工具類
 * @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();
 
 /**
 * 獲取單例對象
 * @return
 */
 public static PropertiesUtil getInstance()
 {
 return instance;
 }
  
 /**
 * 根據key從gzt.properties配置文件獲取配置信息 
 * @param key 鍵值
 * @return
 */
 public String getSysPro(String key){
 return getSysPro(key, null);
 }
 /**
 * 根據key從gzt.properties配置文件獲取配置信息 
 * @param key 鍵值
 * @param defaultValue 默認值
 * @return
 */
 public String getSysPro(String key,String defaultValue){
 return getValue("spring/imageserver-"+System.getProperty("spring.profiles.active")+".properties", key, defaultValue);
 }
 /**
 * 從配置文件中獲取對應key值
 * @param fileName 配置文件名
 * @param key key值
 * @param defaultValue 默認值
 * @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;
 }
}
相關文章
相關標籤/搜索