I want to display images with REST Controller of Java and Spring!

I want to display an image in Java!

This is YuruFuwaFox. I'm studying Java. How can I display the image in Spring REST Controller this time? So I implemented it while researching various things, so I would like to share the method with a memo!

Annotation

This article is for quite a beginner in Java. I'm not for people who are Tsuyotsuyo engineers, so I would appreciate your favor. If you still read it, thank you! (Pointing out what is wrong is also welcome!)

Displaying an image with RESTController? ?? ??

First of all, what is RESTController? I will explain from. RESTController is for so-called API that returns JSON or xml as the return value. It's like passing only data to a normal Controller, which basically returns a View! In other words, if you want to return View, it seems that you can simply pass the image to View and display it somehow, but what should you do with RESTController that returns JSON or xml?

Pass data in binary format

Images can be displayed by passing them as binary data. Therefore, I decided to display the image by passing it in binary format.

Pass the data to HttpEntity and display the image

I will display the image on the browser. Therefore, I will use HttpEntity to put an image in the response body.

showImgService.java


public HttpEntity<[byte]> showImg(String image) throws IOException{
    //Image acquisition
    Resource resource = resourceLoader.getResource("File:" + staticPath + imgPath);
    //For image format acquisition
    String format;
    //For storing byte data
    ByteArrayOutputStream bout;
    //Image to byte data
    try (InputStream img = resource.getInputStream()) {
        format = URLConnection.guessContentTypeFromStream(img);

        bout = new ByteArrayOutputStream();
        int c;
        while ((c = img.read()) != -1) {
            bout.write(c);
        }
    }
    //Extract byte data
    byte[] bytes = bout.toByteArray();

    //Create header
    HttpHeaders headers = new HttpHeaders();
    //Store content information in the header
    headers.setContentType(MediaType.valueOf(format));
    headers.setContentLength(bytes.length);
    //Pass byte data and header to HttpEntity and return
    return new HttpEntity<>(bytes, headers);
}

At the end

It's really a memo, so it's a rough feeling. You can actually convert image byte data in one line by using IOUtils, but this time I forgot, so it looks like this. I hope it helps someone!

Recommended Posts

I want to display images with REST Controller of Java and Spring!
I want to transition screens with kotlin and java!
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
I want to implement various functions with kotlin and java!
I want to return to the previous screen with kotlin and java!
Practice of Java programming basics-I want to display triangles with for statements ①
I want to use java8 forEach with index
Practice of Java programming basics-I want to display triangles with for statements ②
I want to control the start / stop of servers and databases with Alexa
I want to display the name of the poster of the comment
I want to get along with Map [Java beginner]
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
I tried to create a shopping site administrator function / screen with Java and Spring
I tried to summarize the basics of kotlin and java
I tried to verify this and that of Spring @ Transactional
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to narrow down the display of docker ps
[Java] I want to test standard input & standard output with JUnit
I tried to interact with Java
I want to exchange JSON data (object) by Ajax between Java and JavaScript! ~ Spring edition ~
I want to understand the flow of Spring processing request parameters
I want to INSERT Spring Local Time with MySQL Time (also milliseconds)
I want to display the images under assets/images in the production environment
I tried to summarize the methods of Java String and StringBuilder
[Java] I want to perform distinct with the key in the object
I want to control the default error message of Spring Boot
I want to perform asynchronous processing and periodic execution with Rail !!!
How to realize huge file upload with Rest Template of Spring
[Spring Boot] I want to add my own property file and get the value with env.getProperty ().
I want to know the Method of the Controller where the Exception was thrown in the ExceptionHandler of Spring Boot
After 3 months of Java and Spring training
I want to display background-ground-image on heroku.
I want to use DBViewer with Eclipse 2018-12! !!
I want to stop Java updates altogether
I want to display the number of orders for today using datetime.
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
[Ruby] I want to extract only the value of the hash and only the key
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I want to mess with Permission of Windows directory from WSL (ubuntu)
I want to pass the argument of Annotation and the argument of the calling method to aspect
[Ruby] I want to display posted items in order of newest date
I want to display a PDF in Chinese (Korean) with thin reports
I want to ForEach an array with a Lambda expression in Java
I want to get the field name of the [Java] field. (Old tale tone)
[Java Spring MVC] I want to use DI in my own class
I translated the grammar of R and Java [Updated from time to time]
I tried to measure and compare the speed of GraalVM with JMH
I want to test Action Cable with RSpec test
Just input and output images with Spring MVC
I want to output the day of the week
Run R from Java I want to run rJava
I tried to make Basic authentication with Java
I want to send an email in Java.
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
Try to link Ruby and Java with Dapr
I compared the characteristics of Java and .NET
I want to var_dump the contents of the intent
rsync4j --I want to touch rsync in Java.
[Beginner] Upload images and files with Spring [Self-satisfaction]
I want to play with Firestore from Rails