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!
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!)
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?
Images can be displayed by passing them as binary data. Therefore, I decided to display the image by passing it in binary format.
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);
}
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