前段时间研究了图片上传添加水印的效果,现在贴出来供大家参考参考。
/***图片上传,添加水印*@paramrequest*@paramparams*@paramvalues*@return*@throwsException*@authorLLJ*@date/12/16*/public staticList<Map<String, Object>> newUpload(HttpServletRequest request,String[] params, Map<String, Object[]> values)throwsException {List<Map<String, Object>> result =newArrayList<Map<String, Object>>();MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;Map<String, MultipartFile> fileMap = mRequest.getFileMap();String relativePath = FileOperateUtil.UPLOADDIR+ DateUtils.dateStr7(newDate()) +"/";logger.info("图片relativePath:"+relativePath);String uploadDir = request.getSession().getServletContext().getRealPath("/") +"/"+ relativePath;logger.info("图片uploadDir:"+uploadDir);File file =newFile(uploadDir);if(!file.exists()) {file.mkdirs();}String fileName =null;inti = 0;for(Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {Map<String, Object> map =newHashMap<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","图片仅支持小于3M的jpg、png.格式");result.add(map);continue;}//获取文件名 fileName = mFile.getOriginalFilename();if(fileName.lastIndexOf(".")<0 || fileName.lastIndexOf(".")==fileName.length()-1){map.put("success",false);map.put("msg","图片仅支持小于3M的jpg、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 =newFile(uploadDir + storeName);FileCopyUtils.copy(mFile.getBytes(), uploadFile);//固定参数值对 map.put(FileOperateUtil.REALNAME, fileName);map.put(FileOperateUtil.STORENAME, storeName);map.put(FileOperateUtil.SIZE,newFile(zipName).length());map.put(FileOperateUtil.SUFFIX,"zip");map.put(FileOperateUtil.CONTENTTYPE,"application/octet-stream");map.put(FileOperateUtil.CREATETIME,newDate());map.put("url", relativePath + storeName);logger.info("图片url:"+relativePath + storeName);fileName = map.get(FileOperateUtil.STORENAME) +"";/**开始:加水印**/ FileInputStream in=newFileInputStream(uploadDir +"/"+ fileName);Image src=ImageIO.read(in);intw=src.getWidth(null);inth=src.getHeight(null);floatalpha = 0.3f;//透明度BufferedImage img=newBufferedImage(w,h,BufferedImage.TYPE_INT_RGB);//构建画板Graphics2D g=img.createGraphics();//得到画笔g.drawImage(src,0,0,w,h,null);//把源图片写入画板Font fsib30 =newFont("微软雅黑", 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 =newFileOutputStream(uploadDir +"/"+ fileName);JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(out);en.encode(img);/**结束:加水印**///自定义参数值对for(String param : params) {map.put(param, values.get(param)[i]);}result.add(map);}returnresult;}
/** *获取字符长度,一个汉字作为1个字符,一个英文字母作为0.5个字符 *@paramtext*@return字符长度,如:text="中国",返回2;text="test",返回2;text="中国ABC",返回4. */public static intgetLength(String text) {inttextLength = text.length();intlength = textLength;for(inti = 0; i < textLength; i++) {if(String.valueOf(text.charAt(i)).getBytes().length> 1) {length++;}}return(length % 2 == 0) ? length / 2 : length / 2 + 1;}