1

I have the following code to send images to the client :

@GET
@Path("/images/{image}") @Produces("image/*") 
public Response getImage(@PathParam("image") String image) {
 File f = new File(image);

  if (!f.exists()) {
      throw new WebApplicationException(404);
  }

  String mt = new MimetypesFileTypeMap().getContentType(f);
  return Response.ok(f, mt).build(); 
}

Now, the client will receive the image in which format ? Will it be wrapped in XML, or as raw binary ? If I simply put the response in the src of an image tag, will the image be rendered ?

If not, how can I make the raw binary stream that is returned, into an image that can be placed in an img tag

Daud
  • 7,429
  • 18
  • 68
  • 115

2 Answers2

2

ad 1) File will be serialized as raw binary (opened stream will be directly returned)

ad 2) you mean location of the resource which is returning image as a file, right? if so, then the answer is yes (you can't just put raw binary data into html page like "<img src="<binary_data>" />)

Pavel Bucek
  • 5,304
  • 27
  • 44
  • Thanks. But if I am making an Ajax request for the resource, and I am getting back a raw stream, how can I make an image tag display that image ? – Daud Feb 09 '12 at 12:50
  • 2
    @Daud: That sounds like a separate question. (It's a client-side problem, not a server-side problem.) – Donal Fellows Feb 09 '12 at 13:13
  • Just for record, you can return the binary data Base64 encoded, that way you can put the base64 encoded data direct on the src of the img tag. See: https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html – Renato Oliveira Aug 20 '18 at 22:30
0

You can also add content type to your response header e.g. image/jpeg , image/png or image/gif so that the client can decide for himself as to what is the type of image by reading the response header. One more thing if the url you are posting to is returning image stream there is no need for an ajax request. If its a servlet you can jsut add the servlet url to image src, and it'll work.

Ujjwal Pathak
  • 646
  • 12
  • 21