如何在Spring Boot中实现图像上传和处理

简介: 如何在Spring Boot中实现图像上传和处理

如何在Spring Boot中实现图像上传和处理

今天我们将深入探讨如何在Spring Boot应用中实现图像上传和处理的技术细节。

一、图像上传

1. 上传接口设计

首先,我们需要设计一个REST接口来处理图像上传。使用Spring Boot,我们可以轻松地创建一个Controller来处理上传请求。

package cn.juwatech.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/images")
public class ImageUploadController {
   

    private static final String UPLOAD_DIR = "./uploads";

    @Autowired
    private ImageStorageService imageStorageService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
   
        String fileName = imageStorageService.storeImage(file);
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/api/images/download/")
                .path(fileName)
                .toUriString();
        return ResponseEntity.ok().body("文件上传成功:" + fileDownloadUri);
    }

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadImage(@PathVariable String fileName) throws MalformedURLException {
   
        Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
        Resource resource = new UrlResource(filePath.toUri());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
}

2. 图像存储服务

实现一个服务来处理图像的存储和管理。在这里,我们将图像存储在本地文件系统中。

package cn.juwatech.example;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class ImageStorageService {
   

    private static final String UPLOAD_DIR = "./uploads";

    public String storeImage(MultipartFile file) throws IOException {
   
        Path uploadPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(uploadPath)) {
   
            Files.createDirectories(uploadPath);
        }

        String originalFileName = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + "_" + originalFileName;
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);

        return fileName;
    }
}

二、图像处理

1. 图像处理工具

除了上传外,有时我们还需要在应用中对图像进行处理,例如缩放、裁剪、添加水印等操作。以下是一个简单的图像处理示例。

package cn.juwatech.example;

import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@Component
public class ImageProcessingService {
   

    public void resizeImage(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight)
            throws IOException {
   
        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);
        BufferedImage outputImage = new BufferedImage(scaledWidth, scaledHeight, inputImage.getType());

        Graphics2D g2d = outputImage.createGraphics();
        g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();

        String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1);
        ImageIO.write(outputImage, formatName, new File(outputImagePath));
    }
}

2. 在Controller中调用图像处理服务

在Controller中调用图像处理服务,例如实现图像缩放的功能:

package cn.juwatech.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/api/images")
public class ImageProcessingController {
   

    @Autowired
    private ImageProcessingService imageProcessingService;

    @PostMapping("/resize")
    public ResponseEntity<String> resizeImage(@RequestParam("inputImage") String inputImage,
                                              @RequestParam("outputImage") String outputImage,
                                              @RequestParam("width") int width,
                                              @RequestParam("height") int height) throws IOException {
   
        imageProcessingService.resizeImage(inputImage, outputImage, width, height);
        return ResponseEntity.ok().body("图像缩放成功!");
    }
}

三、总结

通过本文的讲解,我们学习了如何在Spring Boot应用中实现图像上传和简单的图像处理功能。从创建REST接口处理上传请求到存储图像,再到使用图像处理服务对图像进行操作,Spring Boot为我们提供了强大的支持和便捷的开发体验,帮助我们快速实现复杂的图像处理需求。

相关文章
Springboot接口同时支持GET和POST请求
Springboot接口同时支持GET和POST请求
1618 0
|
存储 Java
Springboot 验证码生成和校验,图片格式和base64编码串
Springboot 验证码生成和校验,图片格式和base64编码串
1319 0
Springboot 验证码生成和校验,图片格式和base64编码串
|
SQL Java 测试技术
3、Mybatis-Plus 自定义sql语句
这篇文章介绍了如何在Mybatis-Plus框架中使用自定义SQL语句进行数据库操作。内容包括文档结构、编写mapper文件、mapper.xml文件的解释说明、在mapper接口中定义方法、在mapper.xml文件中实现接口方法的SQL语句,以及如何在单元测试中测试自定义的SQL语句,并展示了测试结果。
3、Mybatis-Plus 自定义sql语句
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
缓存 安全 Java
Spring Boot 3 集成 Spring Security + JWT
本文详细介绍了如何使用Spring Boot 3和Spring Security集成JWT,实现前后端分离的安全认证概述了从入门到引入数据库,再到使用JWT的完整流程。列举了项目中用到的关键依赖,如MyBatis-Plus、Hutool等。简要提及了系统配置表、部门表、字典表等表结构。使用Hutool-jwt工具类进行JWT校验。配置忽略路径、禁用CSRF、添加JWT校验过滤器等。实现登录接口,返回token等信息。
6890 14
Spring Boot 3 集成 Spring Security + JWT
|
前端开发 JavaScript Java
Springboot图片上传和映射
Springboot图片上传和映射
509 0
springboot静态资源目录访问,及自定义静态资源路径,index页面的访问
本文介绍了Spring Boot中静态资源的访问位置、如何进行静态资源访问测试、自定义静态资源路径和静态资源请求映射,以及如何处理自定义静态资源映射对index页面访问的影响。提供了两种解决方案:取消自定义静态资源映射或编写Controller来截获index.html的请求并重定向。
springboot静态资源目录访问,及自定义静态资源路径,index页面的访问
|
存储 算法 Java
在Java中使用MD5对用户输入密码进行加密存储、同时登录验证。
这篇文章详细介绍了在Java项目中如何使用MD5算法对用户密码进行加密存储和登录验证,包括加入依赖、编写MD5工具类、注册时的密码加密和登录时的密码验证等步骤,并通过示例代码和数据库存储信息展示了测试效果。
在Java中使用MD5对用户输入密码进行加密存储、同时登录验证。
|
移动开发 小程序 JavaScript
uni-app开发微信小程序
本文详细介绍如何使用 uni-app 开发微信小程序,涵盖需求分析、架构思路及实施方案。主要功能包括用户登录、商品列表展示、商品详情、购物车及订单管理。技术栈采用 uni-app、uView UI 和 RESTful API。文章通过具体示例代码展示了从初始化项目、配置全局样式到实现各页面组件及 API 接口的全过程,并提供了完整的文件结构和配置文件示例。此外,还介绍了微信授权登录及后端接口模拟方法,确保项目的稳定性和安全性。通过本教程,读者可快速掌握使用 uni-app 开发微信小程序的方法。
1064 5
|
存储 缓存 数据库
别再用offset和limit分页了,性能太差!——探索高效分页技术
【8月更文挑战第27天】在Web开发领域,分页是处理大量数据展示时不可或缺的功能。然而,传统的基于offset和limit的分页方式,在数据量剧增时,其性能问题日益凸显。本文将深入探讨这一问题的根源,并介绍几种更为高效的分页策略,助力你的应用性能飞跃。
1199 0

热门文章

最新文章