java图片打文字水印-梁鑫

Posted 向天再借500年V

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java图片打文字水印-梁鑫相关的知识,希望对你有一定的参考价值。

java图片打文字水印-梁鑫

package com.webber.cm.custom.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.webber.cm.custom.feign.StorageServerService;
import com.webber.cm.dto.CmsitesDto;
import com.webber.cm.platform.client.config.service.ConfigClient;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author: liangxin
 * @date: 2022/12/27 10:38
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/text/watermark")
public class TextWatermarkController 

    public static final String ORIGINAL_PIC = "original_pic";

    public static final String LOCAL_TEMP_PATH = "/local/temp";

    @Autowired
    StorageServerService storageServerService;

    @Autowired
    ConfigClient configClient;

    /**
     * 下载 三证合一那个图,
     *
     * @param text
     */
    @GetMapping("/textWatermark")
    public void TextWatermark(@RequestParam(name = "text") String text, HttpServletRequest request, HttpServletResponse response) 
        // 效验
        if (StringUtils.isBlank(text)) 
            try 
                setResponseFailPara(response, "文字水印为空!");
             catch (IOException e) 
                log.info("设置相应信息异常!" + e.getMessage());
            
            return;
        
        String md5 = configClient.getValueByConfigKey(ORIGINAL_PIC, String.class);
        if (StringUtils.isBlank(md5)) 
            try 
                setResponseFailPara(response, "未配置底图!");
             catch (IOException e) 
                log.info("设置相应信息异常!" + e.getMessage());
            
            return;
        
        // 获取文件及文件信息
        CmsitesDto cmsitesDto = storageServerService.getStorageFile(md5);
        String fileName = System.currentTimeMillis() + "";
        if (200 == cmsitesDto.getStatus() && null != cmsitesDto.getData()) 
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(cmsitesDto.getData()));
            fileName = fileName + jsonObject.getString("name");
        
        // 下载到本地,todo 然后做水印
        Response responseFeign = storageServerService.downloadFile(1, md5, "");
        Response.Body body = responseFeign.body();
        InputStream inputStream = null;
        InputStream fileInputStream = null;
        OutputStream outputStream = null;
        OutputStream fileOutputStream = null;
        BufferedImage img = null;
        File file = null;
        try 
            inputStream = body.asInputStream();
            img = ImageIO.read(inputStream);
            // 获取图片的宽 高
            int srcImgWidth = img.getWidth(null);
            int srcImgHeight = img.getHeight(null);
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            // 原图写入
            g.drawImage(img, 0, 0, bufImg.getWidth(), bufImg.getHeight(), null);
            // 根据图片的背景设置水印颜色
            g.setColor(Color.GRAY);
            // 设置字体  画笔字体样式为微软雅黑,加粗,文字大小为60pt
            g.setFont(new Font("微软雅黑", Font.BOLD, 30));
            // 设置水印的坐标(为原图片中间位置)
            // text为水印内容
            int x = (srcImgWidth - getWatermarkLength(text, g)) / 2;
            int y = srcImgHeight / 2;
            // 画出水印 第一个参数是水印内容,第二个参数是x轴坐标,第三个参数是y轴坐标
            g.drawString(text, x, y);
            g.dispose();
            // 然后响应出去;
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.reset();
            String finalFileName = null;
            String userAgent = request.getHeader("USER-AGENT");
            if (userAgent.contains("MSIE")) 
                // IE浏览器
                finalFileName = URLEncoder.encode(fileName, "utf-8");
                finalFileName = finalFileName.replace("+", " ");
             else 
                // 其它浏览器
                finalFileName = URLEncoder.encode(fileName, "utf-8");
                finalFileName = finalFileName.replace("+", "%20");
            
            response.setHeader("Content-disposition", "attachment;filename=\\"" + finalFileName + "\\"");
            response.setContentType("application/x-download");
            // 创建临时文件
            File dir = new File(LOCAL_TEMP_PATH);
            if (!dir.exists()) 
                dir.mkdirs();
            
            file = new File(dir, fileName);
            if (!file.exists()) 
                file.createNewFile();
            
            fileOutputStream = new FileOutputStream(file);
            ImageIO.write(bufImg, "png", fileOutputStream);
            response.setHeader("Content-length", file.length() + "");
            fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            int length = -1;
            byte[] bytes = new byte[1024];
            length = fileInputStream.read(bytes);
            while (length != -1) 
                outputStream.write(bytes, 0, length);
                outputStream.flush();
                length = fileInputStream.read(bytes);
            
         catch (IOException exception) 
            exception.printStackTrace();
         finally 
            try 
                if (outputStream != null) 
                    outputStream.close();
                
                if (inputStream != null) 
                    inputStream.close();
                
                if (fileOutputStream != null) 
                    fileOutputStream.close();
                
                if (fileInputStream != null) 
                    fileInputStream.close();
                
                if (null != file && file.exists()) 
                    file.delete();
                
             catch (IOException e) 
                e.printStackTrace();
            
        
    

    /**
     * 设置失败信息
     *
     * @param response
     * @param msg
     * @throws IOException
     */
    private void setResponseFailPara(HttpServletResponse response, String msg) throws IOException 
        response.setHeader("Content-type", "text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(msg);
    

    /**
     * 获取水印文字的长度
     *
     * @param waterMarkContent
     * @param graphics2D
     * @return
     */
    private static int getWatermarkLength(String waterMarkContent, Graphics2D graphics2D) 
        return graphics2D.getFontMetrics(graphics2D.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    


以上是关于java图片打文字水印-梁鑫的主要内容,如果未能解决你的问题,请参考以下文章

Android 调用系统相机拍照后 添加文字水印

golang 为图片加水印

Thinkphp中文水印和图片水印合体集成插件

java实现给图片添加水印(文字水印或图片水印)

如何快速消除图片上的文字或水印

java图片水印打在图片上