Dynamically create image from JAX-RS servlet

六月ゝ 毕业季﹏ 提交于 2019-12-01 04:50:31

问题


Is it possible to create a PNG image and output it straight to the browser as part of a JAX-RS resource?

Something like this:

@Path("img/{externalId}")
@Stateless
@Produces({"image/png"})
public class MyImgResource {

  @GET
  public Response (@PathParam("externalId") String externalId) {
    // create image, write to buffered output stream

    return Response.ok().entity(stream).build();
  }
}

Would this work? Do I have to take care of the correct headers (Content-Type), or is this done by the @Produces annotation? Can output an image as a Response? Can I build a Response from a stream?


回答1:


Take a look at http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e323:

 @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();
 }


来源:https://stackoverflow.com/questions/5736973/dynamically-create-image-from-jax-rs-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!