如何在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为我们提供了强大的支持和便捷的开发体验,帮助我们快速实现复杂的图像处理需求。

相关文章
|
前端开发 Java Spring
Spring Boot 实现图片上传并回显
Spring Boot 实现图片上传并回显
Springboot接口同时支持GET和POST请求
Springboot接口同时支持GET和POST请求
1347 0
|
JavaScript 小程序 API
【uniApp新模式: 使用Vue3 + Vite4 + Pinia + Axios技术栈构建】
【uniApp新模式: 使用Vue3 + Vite4 + Pinia + Axios技术栈构建】
1388 0
|
前端开发 Java Spring
spring boot中如何实现在手机注册和登录时获取验证码(阿里短信服务)
为了实现在手机注册和登录时获取手机验证码,我使用了阿里的短信服务,下面就来介绍一下具体如何实现。将介绍代码层面如何使用的,去阿里开通该服务,以及如何获得你的accessKeyId和accessKeySecret等。
1513 0
spring boot中如何实现在手机注册和登录时获取验证码(阿里短信服务)
|
SQL 前端开发 JavaScript
分享几个开源Java写的博客系统
分享几个开源Java写的博客系统
5871 0
分享几个开源Java写的博客系统
|
8月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
前端开发 JavaScript Java
Springboot图片上传和映射
Springboot图片上传和映射
368 0
|
10月前
|
Java 开发者 Spring
Java Springboot监听事件和处理事件
通过这些内容的详细介绍和实例解析,希望能帮助您深入理解Spring Boot中的事件机制,并在实际开发中灵活应用,提高系统的可维护性和扩展性。
516 7
springboot静态资源目录访问,及自定义静态资源路径,index页面的访问
本文介绍了Spring Boot中静态资源的访问位置、如何进行静态资源访问测试、自定义静态资源路径和静态资源请求映射,以及如何处理自定义静态资源映射对index页面访问的影响。提供了两种解决方案:取消自定义静态资源映射或编写Controller来截获index.html的请求并重定向。
springboot静态资源目录访问,及自定义静态资源路径,index页面的访问
|
安全 Java 关系型数据库
springboot整合springsecurity,从数据库中认证
本文介绍了如何在SpringBoot应用中整合Spring Security,并从数据库中进行用户认证的完整步骤,包括依赖配置、数据库表创建、用户实体和仓库接口、用户详情服务类、安全配置类、控制器类以及数据库初始化器的实现。
1264 3
springboot整合springsecurity,从数据库中认证