Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an Image from Web Service in Spring

I am facing problem while sending an Image using Spring Web Service.

I have written controller as below

@Controller
public class WebService {

    @RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET)
    public @ResponseBody byte[] getImage() {
        try {
            InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg");
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write( bufferedImage  , "jpg", byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

@ResponseBody converts response into JSON.

I am using RestClient to test Web Service.

But When I'm hitting with http://localhost:8080/my-war-name/rest/image URL.

Header 
Accept=image/jpg

I facing following error on RestClient

Response body conversion to string using windows-1252 encoding failed. Response body not set!

When i'm using browsers Chrome and Firefox

Headers are not added so error was expected (Please guide me on this)

HTTP Status 405 - Request method 'GET' not supported

type Status report

message Request method 'GET' not supported

description The specified HTTP method is not allowed for the requested resource (Request method 'GET' not supported).

I have also faced below error once

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()

I have followed http://krams915.blogspot.com/2011/02/spring-3-rest-web-service-provider-and.html tutorial.

My requirment is to send image in byte format to Android Client.

like image 521
Ketan Avatar asked Dec 28 '11 12:12

Ketan


People also ask

Where do I put pictures in spring?

Bookmark this question. Show activity on this post. so i think i should put images under resources folder i.e under main folder.

What is BufferedImage in Java?

A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).


2 Answers

In addition to answer provided by soulcheck. Spring has added produces property to @RequestMapping annotation. Therefore solution is more easier now:

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = "image/jpg")
public @ResponseBody byte[] getFile()  {
    try {
        // Retrieve image from the classpath.
        InputStream is = this.getClass().getResourceAsStream("/test.jpg"); 

        // Prepare buffered image.
        BufferedImage img = ImageIO.read(is);

        // Create a byte array output stream.
        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        // Write to output stream
        ImageIO.write(img, "jpg", bao);

        return bao.toByteArray();
    } catch (IOException e) {
        logger.error(e);
        throw new RuntimeException(e);
    }
}
like image 159
Taras Matyashovskyy Avatar answered Nov 15 '22 17:11

Taras Matyashovskyy


The answer by #soulcheck is partially right. The configuration won't work in the latest version of Spring as it would clash with mvc-annotation element. Try the below configuration.

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
  </mvc:message-converters>
</mvc:annotation-driven>

Once you have above configuration in your config file. The below code will work:

@RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET)
public @ResponseBody BufferedImage getImage() {
    try {
        InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg");
        return ImageIO.read(inputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
like image 25
jsf Avatar answered Nov 15 '22 17:11

jsf