基于Spring Boot实现图片上传/加水印一把梭操作

简介:

小网红

文章共 537字,阅读大约需要 2分钟 !


概述

很多网站的图片为了版权考虑都加有水印,尤其是那些图片类网站。自己正好最近和图片打交道比较多,因此就探索了一番基于 Spring Boot这把利器来实现从 图片上传 → 图片加水印 的一把梭操作!

注: 本文首发于 My Personal Blog:程序羊,欢迎光临 小站

本文内容脑图如下:

本文内容脑图


搭建 Spring Boot基础工程

过程不再赘述了,这里给出 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>
            <version>2.5</version>
        </dependency>
    </dependencies>

编写文件上传服务

  • 主要就是编写 ImageUploadService 服务

里面仅一个上传图片的方法:uploadImage 方法

    /**
     * 功能:上传图片
     * @param file 文件
     * @param uploadPath 服务器上上传文件的路径
     * @param physicalUploadPath  服务器上上传文件的物理路径
     * @return 上传文件的 URL相对地址
     */
    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();
    }
}

编写图片加水印服务

  • 编写 ImageWatermarkService 服务

里面就一个主要的 watermarkAdd方法,代码后面写有详细解释

@Service
public class ImageWatermarkService {

    /**
     * imgFile 图像文件
     * imageFileName 图像文件名
     * uploadPath 服务器上上传文件的相对路径
     * realUploadPath 服务器上上传文件的物理路径
     */
    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);  // ①
            Graphics2D g = bufferedImage.createGraphics();  // ②
            g.drawImage(image, 0, 0, width,height,null);  // ③

            String logoPath = realUploadPath + "/" + Const.LOGO_FILE_NAME;  // 水印图片地址
            File logo = new File(logoPath);        // 读取水印图片
            Image imageLogo = ImageIO.read(logo);

            int markWidth = imageLogo.getWidth(null);    // 水印图片的宽度和高度
            int markHeight = imageLogo.getHeight(null);

            g.setComposite( AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, Const.ALPHA) );  // 设置水印透明度
            g.rotate(Math.toRadians(-10), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);  // 设置水印图片的旋转度

            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 ) {  // 循环添加多个水印logo
                y = -height / 2;
                while( y < height*count ) {
                    g.drawImage(imageLogo, x, y, null);  // ④
                    y += markHeight + yInterval;
                }
                x += markWidth + xInterval;
            }

            g.dispose();

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

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

        return uploadPath + "/" + imgWithWatermarkFileName;
    }

}

代码思路解释如下:

可以对照代码中的标示数字和下面的解释进行理解:

① 创建缓存图片
② 创建绘图工具
③ 将原图绘制到缓存图片
④ 将水印logo绘制到缓存图片
⑤ 创建图像编码工具类
⑥ 编码缓存图像生成目标图片

可见思路清晰易懂!


编写 图片上传/处理 控制器

我们在该控制器代码中将上述的 图片上传服务图片加水印服务 给用起来:

@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/";  // 服务器上上传文件的相对路径
        String physicalUploadPath = getClass().getClassLoader().getResource(uploadPath).getPath();  // 服务器上上传文件的物理路径

        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);
        return imgInfo;
    }
}

实际实验与效果展示

我们用 Postman工具来辅助我们发出 localhost:9999/watermarktest 请求,进行图片上传的操作:

Postman发请求进行图片上传

之后我们再去项目的资源目录下查看上传的原图加完水印后图片的效果如下:

原图

加完水印后的图片

喔唷,这水印 Logo是不是打的有点多...

不过这下终于不用害怕别人对您的图片侵权啦 !


后记

由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!



目录
相关文章
|
3天前
|
前端开发 JavaScript Java
SpringBoot+Vue+token实现(表单+图片)上传、图片地址保存到数据库。上传图片保存位置自己定义、图片可以在前端回显(一))
这篇文章详细介绍了在SpringBoot+Vue项目中实现表单和图片上传的完整流程,包括前端上传、后端接口处理、数据库保存图片路径,以及前端图片回显的方法,同时探讨了图片资源映射、token验证、过滤器配置等相关问题。
|
3天前
|
前端开发 数据库
SpringBoot+Vue+token实现(表单+图片)上传、图片地址保存到数据库。上传图片保存位置到项目中的静态资源下、图片可以在前端回显(二))
这篇文章是关于如何在SpringBoot+Vue+token的环境下实现表单和图片上传的优化篇,主要改进是将图片保存位置从磁盘指定位置改为项目中的静态资源目录,使得图片资源可以跨环境访问,并在前端正确回显。
|
4天前
|
存储 前端开发 JavaScript
Springboot+Vue实现将图片和表单一起提交到后端,同时将图片地址保存到数据库、再次将存储的图片展示到前端vue页面
本文介绍了使用Springboot后端和Vue前端实现图片与表单数据一起提交到后端,并保存图片地址到数据库,然后展示存储的图片到前端Vue页面的完整流程。
Springboot+Vue实现将图片和表单一起提交到后端,同时将图片地址保存到数据库、再次将存储的图片展示到前端vue页面
|
20天前
|
前端开发 Java 网络架构
SpringBoot使用接口下载图片的写法
在Spring Boot中实现图片下载功能涉及定义一个REST接口来发送图片文件。首先,创建`ImageController`类,并在其中定义`downloadImage`方法,该方法使用`@GetMapping`注解来处理HTTP GET请求。方法内部,通过`Files.readAllBytes`读取图片文件到字节数组,再将该数组封装成`ByteArrayResource`。接着,设置`HttpHeaders`以指定文件名为`image.jpg`并配置为附件下载。
|
1月前
|
文字识别 Java Spring
文本,文字识别,SpringBoot服务开发,SpringBoot如何提供上传服务,接口的设计,它做了将Base64重新转为图片,SpringBoot的应用实例,项目基础搭建
文本,文字识别,SpringBoot服务开发,SpringBoot如何提供上传服务,接口的设计,它做了将Base64重新转为图片,SpringBoot的应用实例,项目基础搭建
|
2月前
|
运维 Java 关系型数据库
Spring运维之boot项目bean属性的绑定读取与校验
Spring运维之boot项目bean属性的绑定读取与校验
36 2
|
2月前
|
存储 运维 Java
Spring运维之boot项目开发关键之日志操作以及用文件记录日志
Spring运维之boot项目开发关键之日志操作以及用文件记录日志
38 2
|
2月前
|
Java Maven
springboot项目打jar包后,如何部署到服务器
springboot项目打jar包后,如何部署到服务器
140 1
|
1月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp小程序的图片推荐系统附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp小程序的图片推荐系统附带文章源码部署视频讲解等
20 0
|
2月前
|
Java Spring
spring练习32-删除用户操作
spring练习32-删除用户操作