Solve the method of adding watermark to uploading pictures in ueditor through background java+SpringMVC

For me, a rookie, I have always been unfamiliar with io. Now the business needs require adding watermarks to pictures in rich text. I checked on Baidu and it is not suitable for my project. I can only study it myself. After two days of research I finally wrote it out, and now I write my method out for everyone to check

1. Because it is written in SpringMVC, SpringMVC provides a MultipartFile class, directly on the code

/**
 * ueditor upload single file
 * @param request
 * @return
 */
@RequestMapping(value = "ueditorUpFile")
public
@ResponseBody
UeditorFormat ueditorUpFile(HttpServletRequest request){
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
   // Get the ID of the uploaded file from config.json
   MultipartFile upfile = multipartRequest.getFile("upfile");
   try {
      InputStream inputStream = upfile.getInputStream();
   } catch (IOException e) {
      e.printStackTrace ();
   }
   //Get the project root path
   String realpath= request.getSession().getServletContext().getRealPath("/");
   if(Objects.nonNull(upfile)){
      //This is my project class, it doesn't matter
      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 {
         //The path to upload to the server, it doesn't matter
         String filepath = sysFileService.genFilePath(2, file.getRandomName(), file.getSuffix());
         //Get the uploaded image
         File tarfile = new File(realpath+upfile.getOriginalFilename());
         try {
            // write the memory image to disk
            upfile.transferTo(tarfile);
            if (!tarfile.getParentFile().exists()) {
               tarfile.getParentFile().mkdir();
            }
            try {
               //add watermark
               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 ();
            }
            //Get the image after adding the watermark
            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 ();
         }
         //Save the watermark image to the server
         file = sysFileService.saveFile(file, upfile, filepath);
         return UeditorFormat.parseSysFile(file);
      } catch (FileUploadFailException e) {
         e.printStackTrace ();
         UeditorFormat uf = new UeditorFormat();
         uf.setState("File upload failed");
         uf.setTitle(upfile.getOriginalFilename());
         return uf;
      }
   } else {
      UeditorFormat uf = new UeditorFormat();
      uf.setState("File upload failed, the uploaded file is empty!");
      uf.setTitle(upfile.getOriginalFilename());
      return uf;
   }
}

I also found this class for adding watermarks from the Internet. It is very easy to use. I will test it myself. Now I will share it with you.

public class WaterMarkGenerate {
    private static final String FONT_FAMILY="Microsoft Yahei";//Font
    private static final int FONT_STYLE=Font.BOLD;//Font bold
    private static final int FONT_SIZE=24;//font size
    private static final float ALPHA=0.7F;//Watermark transparency

    private static final int LOGO_WIDTH=200;//Image watermark size

    //Add text watermark
    /*tarPath: image save path
     *contents:Text watermark content* */
    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);

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

        // watermark position
//      int x=width-strWidth;
//      int y=height-strHeight;

        int x=0,y=0;

        //Set font and watermark transparency
        g.setFont(new Font(FONT_FAMILY,FONT_STYLE,FONT_SIZE));
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA));
//      g.drawString(contents, x, y);
        //rotate the image
        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; //The interval between watermarks is set to 50
        }
        g.dispose();

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

    //Add image watermark
    /*
     * tarPath: image save path
     * logoPath: logo file path
     * */
    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);
        //Create a BufferedImage object with no transparent color
        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);
    }

    //Processing of text length: width conversion of Chinese and English characters of text watermark
    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){ //Chinese characters
                length++;
            }
        }
        length = length%2 == 0?length/2:length/2+1; //Conversion of Chinese and English characters
        return length;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324444452&siteId=291194637