圖片上傳至服務器實現壓縮

 

 

1.縮略圖壓縮文件jar包html

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

 

2.thumbnailator的一些功能java

一、指定大小進行縮放

[java] view plain copy
//size(寬度, 高度)  
  
/* 
 * 若圖片橫比200小,高比300小,不變 
 * 若圖片橫比200小,高比300大,高縮小到300,圖片比例不變 
 * 若圖片橫比200大,高比300小,橫縮小到200,圖片比例不變 
 * 若圖片橫比200大,高比300大,圖片按比例縮小,橫爲200或高爲300 
 */  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(200, 300)  
    .toFile("c:/a380_200x300.jpg");  
  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(2560, 2048)  
    .toFile("c:/a380_2560x2048.jpg");  


二、按照比例進行縮放

[java] view plain copy
//scale(比例)  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .scale(0.25f)  
    .toFile("c:/a380_25%.jpg");  
  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .scale(1.10f)  
    .toFile("c:/a380_110%.jpg");  


三、不按照比例,指定大小進行縮放

[java] view plain copy
//keepAspectRatio(false)默認是按照比例縮放的  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(200,200)  
    .keepAspectRatio(false)  
    .toFile("c:/a380_200x200.jpg");  


四、旋轉

[java] view plain copy
//rotate(角度),正數:順時針負數:逆時針  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .rotate(90)  
    .toFile("c:/a380_rotate+90.jpg");  
  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .rotate(-90)  
    .toFile("c:/a380_rotate-90.jpg");  


五、水印

[java] view plain copy
//watermark(位置,水印圖,透明度)  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(newFile("images/watermark.png")),0.5f)  
    .outputQuality(0.8f)  
    .toFile("c:/a380_watermark_bottom_right.jpg");  
  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .watermark(Positions.CENTER,ImageIO.read(newFile("images/watermark.png")),0.5f)  
    .outputQuality(0.8f)  
    .toFile("c:/a380_watermark_center.jpg");  


六、裁剪

[java] view plain copy
//sourceRegion()  
  
//圖片中心400*400的區域  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .sourceRegion(Positions.CENTER,400,400)  
    .size(200,200)  
    .keepAspectRatio(false)  
    .toFile("c:/a380_region_center.jpg");  
  
//圖片右下400*400的區域  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .sourceRegion(Positions.BOTTOM_RIGHT,400,400)  
    .size(200,200)  
    .keepAspectRatio(false)  
    .toFile("c:/a380_region_bootom_right.jpg");  
  
//指定座標  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .sourceRegion(600,500,400,400)  
    .size(200,200)  
    .keepAspectRatio(false)  
    .toFile("c:/a380_region_coord.jpg");  



七、轉化圖像格式

[java] view plain copy
//outputFormat(圖像格式)  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .outputFormat("png")  
    .toFile("c:/a380_1280x1024.png");  
  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .outputFormat("gif")  
    .toFile("c:/a380_1280x1024.gif");  
 

八、輸出到OutputStream

[java] view plain copy
//toOutputStream(流對象)  
OutputStreamos=newFileOutputStream("c:/a380_1280x1024_OutputStream.png");  
Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .toOutputStream(os);  
 

 九、輸出到BufferedImage

[java] view plain copy
//asBufferedImage()返回BufferedImage  
BufferedImagethumbnail=Thumbnails.of("images/a380_1280x1024.jpg")  
    .size(1280,1024)  
    .asBufferedImage();  
ImageIO.write(thumbnail,"jpg",newFile("c:/a380_1280x1024_BufferedImage.jpg"));

 

3.java代碼實現linux

private static Logger log = LoggerFactory.getLogger(ActivitySpringArticleController.class);
	
	@ApiOperation(value="圖片上傳接口")
	@RequestMapping(value = "activity/uploadActivitySpringFile")
	@ResponseBody
	public String uploadActivitySpringFile(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	    MultipartFile imageFile = multipartRequest.getFile("upfile");
	    if(imageFile == null ){
	    	throw new BusinessException(new ErrorCode("imageFile不能爲空"));
        }
        
        if (imageFile.getSize() >= 10*1024*1024)
        {
        	throw new BusinessException(new ErrorCode("文件不能大於10M"));
        }
        String uuid = UUID.randomUUID().toString();
        
        String fileDirectory = DateUtil.date2String(new Date(), DateUtil.SIMPLE_DATE_FORMAT);
        
        //拼接後臺文件名稱
        String pathName = fileDirectory + File.separator + uuid + "."
                            + FilenameUtils.getExtension(imageFile.getOriginalFilename());
        //構建保存文件路勁
        //2016-5-6 yangkang 修改上傳路徑爲服務器上 
      //  String realPath = request.getServletContext().getRealPath("uploadPath");
        String realPath = "D://test//";
        //獲取服務器絕對路徑 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;
            throw new BusinessException(new ErrorCode("操做失敗"));
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                filePathName = null;
                throw new BusinessException(new ErrorCode("操做失敗"));
            } 
         }
    
        
        //        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(11, 12).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) {
        	 throw new BusinessException(new ErrorCode("操做失敗"));
        }
        /**
         * 縮略圖end
         */
        
        Map<String, Object> map = new HashMap<String, Object>();
        //原圖地址
        map.put("originalUrl", pathName);
        //縮略圖地址
        map.put("thumbnailUrl", thumbnailPathName);
        return pathName+"---------"+thumbnailPathName;
        //throw new BusinessException(new ErrorCode("操做成功"));
    }

 

 

4.配置文件,爲上傳至linux使用spring

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

  /**
     * 根據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);
    }
例:

        //獲取服務器絕對路徑 linux 服務器地址   
        String urlString=PropertiesUtil.getInstance().getSysPro("uploadPath");

 

5.工具類緩存

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;
    }
}

 

 6. 測試服務器

 

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="activity/downloadActivitySpringFile" method="POST" enctype="multipart/form-data">
    文件:<input type="file" name="upfile"/>
    <input type="submit" />
</form>
<a href="activity/downloadActivitySpringFile">下載test</a>
<p>多文件上傳</p>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p><input type="submit" value="上傳" /></p>
</form>
</body>
</html>
相關文章
相關標籤/搜索