解决在ueditor中上传图片通过后台java+SpringMVC添加水印方法

对于我一个菜鸟来说,以前一直对io这块不熟悉,现在业务需求要求对富文本中的图片添加水印,在百度上查了都不是适合我的项目,只能自己研究,研究了俩天终于写了出来,现在我把我的方法写出来,供大家查阅

1.因为是在SpringMVC里面写的,SpringMVC提供了一个MultipartFile类,直接上代码

/**
 * ueditor上传单文件
 * @param request
 * @return
 */
@RequestMapping(value = "ueditorUpFile")
public 
@ResponseBody
UeditorFormat ueditorUpFile(HttpServletRequest request){
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
   // 从config.json中取得上传文件的ID
   MultipartFile upfile = multipartRequest.getFile("upfile");
   try {
      InputStream inputStream = upfile.getInputStream();
   } catch (IOException e) {
      e.printStackTrace();
   }
   //获取项目根路径
   String realpath= request.getSession().getServletContext().getRealPath("/");
   if(Objects.nonNull(upfile)){
      //这个是我的项目类,没有关系
      SysFile file = new SysFile();
      file.setCreateDate(new Date());
      file.setName(upfile.getOriginalFilename());
      file.setRandomName(IdGen.uuid());
      file.setStatus(SysFile.TEMP_FILE);
      file.setSuffix(file.getName().substring(file.getName().lastIndexOf(".")));
      file.setSize(upfile.getSize());
      try {
         //上传到服务器的路径,没有关系
         String filepath = sysFileService.genFilePath(2, file.getRandomName(), file.getSuffix());
         //获取上传的图片
         File tarfile = new File(realpath+upfile.getOriginalFilename());
         try {
            //把内存图片写入磁盘中
            upfile.transferTo(tarfile);
            if (!tarfile.getParentFile().exists()) {
               tarfile.getParentFile().mkdir();
            }
            try {
               //添加水印
               WaterMarkGenerate.generateWithImageMark(tarfile,realpath+File.separator+"upload"+File.separator+file.getRandomName()+file.getSuffix(),realpath+File.separator+"static"+File.separator+"images"+File.separator+"watermark.png");
            } catch (Exception e) {
               e.printStackTrace();
            }
            //获取添加水印后的图片
            File newFile = new File(realpath+File.separator+"upload"+File.separator+file.getRandomName()+file.getSuffix());
            FileInputStream input = new FileInputStream(newFile);
            MultipartFile multipartFile = new MockMultipartFile("file",
                  file.getName(), "text/plain", IOUtils.toByteArray(input));
            upfile = multipartFile;
         } catch (IOException e) {
            e.printStackTrace();
         }
         //水印图片保存到服务器
         file = sysFileService.saveFile(file, upfile, filepath);
         return UeditorFormat.parseSysFile(file);
      } catch (FileUploadFailException e) {
         e.printStackTrace();
         UeditorFormat uf = new UeditorFormat();
         uf.setState("文件上传失败");
         uf.setTitle(upfile.getOriginalFilename());
         return uf;
      }
   } else {
      UeditorFormat uf = new UeditorFormat();
      uf.setState("文件上传失败,上传的文件为空!");
      uf.setTitle(upfile.getOriginalFilename());
      return uf;
   }
}

这个添加水印的类也是我从网上找的,特别好用,亲测,现在分享给大家

public class WaterMarkGenerate {
    private static final String FONT_FAMILY="微软雅黑";//字体
    private static final int FONT_STYLE=Font.BOLD;//字体加粗
    private static final int FONT_SIZE=24;//字体大小
    private static final float ALPHA=0.7F;//水印透明度

    private static final int LOGO_WIDTH=200;//图片水印大小

    //添加文字水印
    /*tarPath:图片保存路径
     *contents:文字水印内容* */
    public static void generateWithTextMark(File srcFile,
                                            String tarPath,String contents) throws Exception{
        Image srcImage=ImageIO.read(srcFile);
        int width=srcImage.getWidth(null);
        int height=srcImage.getHeight(null);

        BufferedImage tarBuffImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g=tarBuffImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width,height,null);

        //计算
        int strWidth=FONT_SIZE*getTextLength(contents);
        int strHeight=FONT_SIZE;

        //水印位置
//      int x=width-strWidth;
//      int y=height-strHeight;

        int x=0,y=0;

        //设置字体和水印透明度
        g.setFont(new Font(FONT_FAMILY,FONT_STYLE,FONT_SIZE));
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));
//      g.drawString(contents, x, y);
        //旋转图片
        g.rotate(Math.toRadians(-30),width/2,height/2);
        while(x < width*1.5){
            y = -height/2;
            while(y < height*1.5){
                g.drawString(contents,x,y);
                y += strHeight + 50;
            }
            x += strWidth + 50; //水印之间的间隔设为50
        }
        g.dispose();

        JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(new FileOutputStream(tarPath));
        en.encode(tarBuffImage);
    }

    //添加图片水印
    /*
     * tarPath:图片保存路径
     * logoPath:logo文件路径
     * */
    public static void generateWithImageMark(File srcFile,
                                             String tarPath,String logoPath) throws Exception{
        Image srcImage=ImageIO.read(srcFile);
        int width=srcImage.getWidth(null);
        int height=srcImage.getHeight(null);
        //创建一个不带透明色的BufferedImage对象
        BufferedImage tarBuffImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g=tarBuffImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width,height,null);

        Image logoImage= ImageIO.read(new File(logoPath));
        int logoWidth=LOGO_WIDTH;
        int logoHeight=(LOGO_WIDTH*logoImage.getHeight(null))/logoImage.getWidth(null);

        int x=width-logoWidth;
        int y=height-logoHeight;

        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));
        g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);
        g.dispose();

        JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(new FileOutputStream(tarPath));
        en.encode(tarBuffImage);
    }

    //文本长度的处理:文字水印的中英文字符的宽度转换
    public static int getTextLength(String text){
        int length = text.length();
        for(int i=0;i<text.length();i++){
            String s = String.valueOf(text.charAt(i));
            if(s.getBytes().length>1){  //中文字符
                length++;
            }
        }
        length = length%2 == 0?length/2:length/2+1;  //中文和英文字符的转换
        return length;
    }
}

猜你喜欢

转载自my.oschina.net/u/3759357/blog/1789390