1. 程式人生 > >java 上傳圖片以及壓縮圖片大小

java 上傳圖片以及壓縮圖片大小

縮圖壓縮檔案jar包

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

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

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

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

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

圖片尺寸不變,壓縮圖片檔案大小

        //圖片尺寸不變,壓縮圖片檔案大小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);
    }