您现在的位置是: 首页> java > 正文

springboot进行图片上传和添加水印

时间: 2020-12-07 00:10:12 来源:网络 作者:自由 分类:java
简介:

srpingboot图片上传和给牵扯到版权或者私密的图片进行添加上水印

 

1.首先先看一下Controller该如何写

@CrossOrigin
@RestController
@RequestMapping("/uploadImage")
public class UploadController {

    @RequestMapping(value = "/uplaod", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public HashMap<String, Object> uplaod(HttpServletRequest request, @RequestParam("img") MultipartFile file, @RequestParam("type") String type) {

        HashMap<String, Object> result = new HashMap<String, Object>();
        //想要存储文件的地址
        String pathName = "upload/";
        // 定义文件全路径
        String pathFullName="";
        File filePath = new File(pathName);
        // 判断目录是否存在,如果不存在,创建文件目录
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println("目录不存在,创建目录:" + filePath);
            filePath.mkdirs();
        }
        // 定义一个uuid用来保存图片的名字,也可以根据自己的需求来定义保存文件的名字
        UUID uuid = UUID.randomUUID();
        //获取文件名(包括后缀)
        String uploadName = file.getOriginalFilename();
        // 取得文件名后缀
        String suffix = uploadName.substring(uploadName.lastIndexOf(".") + 1);

        pathFullName = pathName + uuid.toString() + "." + suffix;

        SysDict sysDict = new SysDict();
        sysDict.setDictCode(type);
        SysDict resDict = sysDictService.getSysDict(sysDict);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathFullName);
            fos.write(file.getBytes()); // 写入文件

            // 添加水印
            String srcImgPath = pathFullName; //源图片地址
            String tarImgPath = pathFullName; //待存储的地址
            //格式化时间
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = f.format(new Date());
            String waterMarkContent = "要添加的水印内容";  //水印内容

            WaterMarkUtil.markImage(waterMarkContent, pathName, tarImgPath);

            //System.out.println("文件上传成功");
            HashMap<String, String> data = new HashMap<String, String>();
            result.put("code", "200");
            data.put("url", apiUrl + pathName);
            result.put("data", data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0");
            return result;
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.创建WaterMarkUtil.java的工具类,添加水印用


package com.ten.ms.tmsframework.common.Util;


import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;

public class WaterMarkUtil {
    // 水印透明度
    private static float alpha = 0.3f;
    // 水印横向位置
    private static int positionWidth = 50;
    // 水印纵向位置
    private static int positionHeight = 100;
    // 水印文字字体
    private static Font font = new Font("宋体", Font.BOLD, 60);
    // 水印文字颜色
    private static Color color = Color.red;

    /**
     * 给图片添加水印文字
     *
     * @param text       水印文字
     * @param srcImgPath 源图片路径
     * @param targetPath 目标图片路径
     */
    public static void markImage(String text, String srcImgPath, String targetPath) {
        markImage(text, srcImgPath, targetPath, null);
    }

    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     *
     * @param text 水印文字
     * @param srcImgPath 源图片路径
     * @param targetPath 目标图片路径
     * @param degree 水印旋转
     */
    public static void markImage(String text, String srcImgPath, String targetPath, Integer degree) {

        OutputStream os = null;
        try {
            // 0、图片类型
            String type = srcImgPath.substring(srcImgPath.indexOf(".") + 1, srcImgPath.length());

            // 1、源图片
            Image srcImg = ImageIO.read(new File(srcImgPath));

            int imgWidth = srcImg.getWidth(null);
            int imgHeight = srcImg.getHeight(null);

            BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(font);
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)

            //设置水印的坐标
            int x = imgWidth - 2*getWatermarkLength(text, g);
            int y = imgHeight - 2*getWatermarkLength(text, g);
            g.drawString(text, x, y);  //画出水印
//            g.drawString(text, positionWidth, positionHeight);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(targetPath);
            // ImageIO.write(buffImg, "JPG", os);
            ImageIO.write(buffImg, type.toUpperCase(), os);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     * @param text 水印文字
     * @param inputStream 源图片路径
     * @param outputStream 目标图片路径
     * @param degree 水印旋转
     * @param typeName
     */
    public static void markImageByIO(String text, InputStream inputStream, OutputStream outputStream,
                                     Integer degree, String typeName) {
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(inputStream);

            int imgWidth = srcImg.getWidth(null);
            int imgHeight = srcImg.getHeight(null);
            BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(font);
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)

            g.drawString(text, positionWidth, positionHeight);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            ImageIO.write(buffImg, typeName.toUpperCase(), outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
}

3.编写element ui前台html代码

<el-upload class="text_uploader" 
 :show-file-list="false" 
 :before-upload="beforeUpload" // 上传之前执行的方法
 :on-success="onSuccess" //成功后执行的方法
 :on-error="onError" 
 :action="后台url地址">

  <el-button :disabled="importDataDisabled" type="success" :icon="importDataBtnIcon">
    按钮
  </el-button>
</el-upload>​

 

总结

       java的上传图片和加水印基本上使用这些就可以了,大家也可以把加水印和图片上传抽成一个共同的方法方便以后开发项目的时候继续使用。后续我会分享更多的技术相关的内容,请大家多多关注。

 

 

标签:java

文章声明
版权声明:本文为作者原创,仅用于本站访客学习、研究和交流目的,未经授权禁止转载
联系 作者

一个90后草根站长!13年入行。一直潜心研究技术,一边工作一边积累经验,分享一些个人后端技术(java、python、c#、php等),以及前端相关等心得。