1. 程式人生 > >java實現圖片上傳並新增水印demo

java實現圖片上傳並新增水印demo

前段時間研究了圖片上傳新增水印的效果,現在貼出來供大家參考參考。
/**
 * 圖片上傳,新增水印
* @param request
* @param params
* @param values
* @return
* @throws Exception
 * @author LLJ
 * @date 2016/12/16
 */
public static List<Map<String, Object>> newUpload(HttpServletRequest request,
      String[] params, Map<String, Object[]> values) throws 
Exception { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = mRequest.getFileMap(); String relativePath = FileOperateUtil.UPLOADDIR
+ DateUtils.dateStr7(new Date()) + "/"; logger.info("圖片relativePath:"+relativePath); String uploadDir = request.getSession().getServletContext().getRealPath("/") + "/" + relativePath; logger.info("圖片uploadDir:"+uploadDir); File file = new File(uploadDir); if (!file.exists()) { file.mkdirs(); } String fileName = null
; int i = 0; for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("success", true); Map.Entry<String, MultipartFile> entry = it.next(); MultipartFile mFile = entry.getValue(); //判斷檔案格式 和 檔案大小 if(mFile.getSize()/1024D>NEW_LIMIT_SIZE){ map.put("success", false); map.put("msg", "圖片僅支援小於3Mjpg png.格式"); result.add(map); continue; } //獲取檔名 fileName = mFile.getOriginalFilename(); if(fileName.lastIndexOf(".")<0 || fileName.lastIndexOf(".")==fileName.length()-1){ map.put("success", false); map.put("msg", "圖片僅支援小於3Mjpg png.格式"); result.add(map); continue; } if(!Pattern.matches("^"+NEW_LIMIT_TYPE+"$", fileName.substring(fileName.lastIndexOf(".")+1))){ map.put("success", false); map.put("msg", "檔案上傳格式不對,只支援jpg png格式"); result.add(map); continue; } String storeName = rename(fileName); String noZipName = uploadDir + storeName; String zipName = zipName(noZipName); logger.info("圖片zipName:"+zipName); File uploadFile = new File(uploadDir + storeName); FileCopyUtils.copy(mFile.getBytes(), uploadFile); // 固定引數值對 map.put(FileOperateUtil.REALNAME, fileName); map.put(FileOperateUtil.STORENAME, storeName); map.put(FileOperateUtil.SIZE, new File(zipName).length()); map.put(FileOperateUtil.SUFFIX, "zip"); map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream"); map.put(FileOperateUtil.CREATETIME, new Date()); map.put("url", relativePath + storeName); logger.info("圖片url:"+relativePath + storeName); fileName = map.get(FileOperateUtil.STORENAME) + ""; /**開始:加水印**/ FileInputStream in=new FileInputStream(uploadDir + "/" + fileName); Image src=ImageIO.read(in); int w=src.getWidth(null); int h=src.getHeight(null); float alpha = 0.3f; // 透明度 BufferedImage img=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);//構建畫板 Graphics2D g=img.createGraphics();//得到畫筆 g.drawImage(src,0,0,w,h,null);//把源圖片寫入畫板 Font fsib30 = new Font("微軟雅黑", Font.BOLD + Font.ITALIC, img.getWidth()/16); g.setFont(fsib30); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha)); g.setColor(Color.black); g.setBackground(Color.white); g.rotate(Math.toRadians(-15), (double) img.getWidth() / 2, (double) img .getHeight() / 2); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); String pressText = "僅供XXX認證使用"; g.drawString(pressText, (w - (getLength(pressText) * img.getWidth()/16)) / 2 + 10, (h - img.getWidth()/16) / 2 + 10); g.dispose();//生成圖片 OutputStream out = new FileOutputStream(uploadDir + "/" + fileName); JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(out); en.encode(img); /**結束:加水印**/ // 自定義引數值對 for (String param : params) { map.put(param, values.get(param)[i]); } result.add(map); } return result; }
/**
    * 獲取字元長度,一個漢字作為 1 個字元, 一個英文字母作為 0.5 個字元
* @param text
* @return 字元長度,如:text="中國",返回 2text="test",返回 2text="中國ABC",返回 4.
    */
public static int getLength(String text) {
       int textLength = text.length();
       int length = textLength;
       for (int i = 0; i < textLength; i++) {
           if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
               length++;
           }
       }
       return (length % 2 == 0) ? length / 2 : length / 2 + 1;
   }