前段时间研究了图片上传添加水印的效果,现在贴出来供大家参考参考。
/**
* 图片上传,添加水印
* @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", "图片仅支持小于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 = 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="中国",返回 2;text="test",返回 2;text="中国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;
}