The article has 537 words and takes about 2 minutes to read!


An overview of the

A lot of website images are watermarked for copyright consideration, especially those image sites. Oneself just recently and the picture deal with more, therefore explored a kind of based on Spring Boot this sharp tool to realize from the picture upload to picture add watermark a shuttle operation!

Welcome to My Personal Blog

The brain map of this paper is as follows:


Set up the Spring Boot foundation project

Without further elaboration of the process, here are the key dependencies in the POM:

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> The < version > 2.5 < / version > < / dependency > < / dependencies >Copy the code

Write a file upload service

  • Basically writing the ImageUploadService service

There is only one method for uploading images: the uploadImage method

    /** * function: upload image *@paramThe file file *@paramUploadPath specifies the file uploadPath *@paramPhysicalUploadPath Physical path for uploading files *@returnThe relative URL of the uploaded file */
    public String uploadImage( MultipartFile file, String uploadPath, String physicalUploadPath ) {

        String filePath = physicalUploadPath + file.getOriginalFilename();

        try {
            File targetFile=new File(filePath);
            FileUtils.writeByteArrayToFile(targetFile, file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadPath + "/"+ file.getOriginalFilename(); }}Copy the code

Prepare a picture watermarking service

  • Write the ImageWatermarkService service

There is a main watermarkAdd method, which is explained in detail at the back of the code

@Service
public class ImageWatermarkService {

    /** * imgFile image file * imageFileName imageFileName * uploadPath relative path of uploaded files on the server * realUploadPath physical path of uploaded files on the server */
    public String watermarkAdd( File imgFile, String imageFileName, String uploadPath, String realUploadPath ) {

        String imgWithWatermarkFileName = "watermark_" + imageFileName;
        OutputStream os = null;

        try {
            Image image = ImageIO.read(imgFile);

            int width = image.getWidth(null);
            int height = image.getHeight(null);

            BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);  / / 1.
            Graphics2D g = bufferedImage.createGraphics();  / / 2.
            g.drawImage(image, 0.0, width,height,null);  / / 3.

            String logoPath = realUploadPath + "/" + Const.LOGO_FILE_NAME;  // Watermark the image address
            File logo = new File(logoPath);        // Read the watermark image
            Image imageLogo = ImageIO.read(logo);

            int markWidth = imageLogo.getWidth(null);    // The width and height of the watermark image
            int markHeight = imageLogo.getHeight(null);

            g.setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, Const.ALPHA) );  // Set the watermark transparency
            g.rotate(Math.toRadians(-10), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);  // Set the rotation of the watermark image

            int x = Const.X;
            int y = Const.Y;

            int xInterval = Const.X_INTERVAL;
            int yInterval = Const.Y_INTERVAL;

            double count = 1.5;
            while ( x < width*count ) {  // Add multiple watermark logos in a loop
                y = -height / 2;
                while( y < height*count ) {
                    g.drawImage(imageLogo, x, y, null);  / / 4.
                    y += markHeight + yInterval;
                }
                x += markWidth + xInterval;
            }

            g.dispose();

            os = new FileOutputStream(realUploadPath + "/" + imgWithWatermarkFileName);
            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os); / / 5.
            en.encode(bufferedImage); / / 6.

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(os! =null) {try {
                    os.close();
                } catch(IOException e) { e.printStackTrace(); }}}return uploadPath + "/"+ imgWithWatermarkFileName; }}Copy the code

The code is explained as follows:

It can be understood by reference to the number of identifiers in the code and the following explanation:

① Create a cache image ② create a drawing tool ③ draw the original image to the cache image ④ Draw the watermark logo to the cache image ⑤ Create an image coding tool class ⑥ Encode the cache image to generate the target image

Visible thinking clear and easy to understand!


Write picture upload/processing controller

We use the above image upload service and image watermarking service in the controller code:

@RestController
public class WatermarkController {

    @Autowired
    private ImageUploadService imageUploadService;

    @Autowired
    private ImageWatermarkService watermarkService;

    @RequestMapping(value = "/watermarktest", method = RequestMethod.POST)
    public ImageInfo watermarkTest( @RequestParam("file") MultipartFile image ) {

        ImageInfo imgInfo = new ImageInfo();

        String uploadPath = "static/images/"; // The relative path to upload files on the server String physicalUploadPath = getClass().getClassLoader().getResource(uploadPath).getPath(); / / upload files on the server physical path String imageURL = imageUploadService. UploadImage (image, uploadPath physicalUploadPath); File imageFile = new File(physicalUploadPath + image.getOriginalFilename() ); String watermarkAddImageURL = watermarkService.watermarkAdd(imageFile, image.getOriginalFilename(), uploadPath, physicalUploadPath); imgInfo.setImageUrl(imageURL); imgInfo.setLogoImageUrl(watermarkAddImageURL);returnimgInfo; }}Copy the code

Practical experiment and effect demonstration

We use the Postman tool to assist localhost: we send you 9999 / watermarktest request, for the operation of the image upload:

Then we went to the resource directory of the project to check the uploaded original image and the effect of the watermarked image as follows:

Wow, isn’t that watermark Logo a little too much…

But this finally need not be afraid of others to your picture infringement!


Afterword.

Due to the limited ability, if there is a mistake or improper place, please also criticize and correct, study together!

  • My Personal Blog: CodeSheep program sheep
  • My six months of tech blogging


To subscribe to CodeSheep’s public account, long press or scan below, you can get more practical, understandable and reproducible original articles