Returning Image/Media Data with Spring MVC

Spring MVC is a popular framework to build web applications in Java. One of the common requirements in web development is handling image or media data such as pictures, videos, or audio files.

In Spring MVC, handling image or media data involves configuring a controller to receive requests for specific resources and then serving those resources to clients. We will use the @Controller annotation to define the controller class, and it can utilize methods annotated with @RequestMapping to map incoming requests to appropriate handlers. We will load the image from the file system or database within these handlers and return it as the response.

Key Terminologies:

  • Spring MVC: Spring MVC, short for Model-View-Controller, is a framework within the Spring Framework for building web applications and RESTful web services in Java.
  • Controller: It handles incoming HTTP requests, processes them, and generates the appropriate response. It’s typically annotated with @Controller and contains methods annotated with @RequestMapping or other handler annotations.
  • RequestMapping: This is an annotation used in Spring MVC to map HTTP requests to specific handler methods within the controller class. It allows developers to define URL patterns that trigger the execution of particular methods.
  • ResponseEntity: It is a class in Spring MVC representing the HTTP response. It allows developers to control the HTTP status code, headers, and body of the response returned by the controller method.
  • MediaType: It is an enum class in the Spring Framework representing standard MIME types. It’s commonly used to specify the content type of HTTP requests and responses, such as JSON, XML, HTML, or image formats like JPEG and PNG.

Implementation to Return Image/Media Data with Spring MVC

Step 1: Create the new Spring Boot project using Spring initializer on creating the project including the below dependencies into the project.

Dependencies

  • Spring Web
  • Spring DevTools
  • Lombok

Once create the project then the file structure looks like the below image.


Step 2: Resource Image

We will save the sample image at the location of the below path.

Go to src > java > resources > static > images > image.png and save the sample image.

Step 3: Create the Image Controller class

Go to src > org.example.springimagedemo > controller > ImageController and put the below code.

Java
package org.example.springimagedemo.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.nio.file.Files;

@Controller
public class ImageController {

    @GetMapping("/image")
    public ResponseEntity<byte[]> getImage() throws IOException {
        // Load image data
        ClassPathResource resource = new ClassPathResource("static/images/image.png");
        byte[] imageData = Files.readAllBytes(resource.getFile().toPath());

        // Set content type header
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        // Return image data as ResponseEntity
        return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
    }
}


Step 4: Main Class

No need to change the main class of the application.

Java
package org.example.springimagedemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringImageDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringImageDemoApplication.class, args);
    }
}


Step 5: Run the Application

Once we run the application, then the project will run at port 8080.


Output:

Endpoint: http://localhost:8080/image

When we open above URL in browser, we will see the below image as result.

This example project demonstrates how to serve the image named image.png located in the resource path. When a GET request is made to /image, the controller loads the image data and returns it as the response with the appropriate content-type header.