Jax-RS从byte []生成图像

时间:2014-03-05 13:59:19

标签: java json jax-rs

我正在尝试在用户点击网址时显示图片http://localhost:8080/app/profile/getImage/5315d33284aec8c202eef15a它应该显示ID为5315d33284aec8c202eef15a的图像。

My service is 



@GET
    @Path("/getImage/{id}")
    @Produces({"image/*"})
    public Response getImage(@PathParam("id") final String id)
    {
        ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR);
        try
        {

            final byte[] imageBytes = getImageBytes(id);
 System.out.println("image length "+imageBytes.length);
            builder.status(Status.OK).entity(new StreamingOutput(){
                @Override
                public void write(OutputStream output) throws IOException, WebApplicationException
                {
                    output.write(imageBytes);
                    output.flush();

                }

            });
        }
        catch (Exception e)
        {
          System.out.println("exception "+e);
        }
        return builder.build();
    }

但它不会产生图像。System.out.println("image length "+imageBytes.length);给出输出=>图片长度72240我失踪的地方?

1 个答案:

答案 0 :(得分:1)

您需要指定要生成的图像的类型。将.type("image/png")添加到ResponseBuilder以获取PNG图片。

builder.status(Status.OK).type("image/png").entity(new StreamingOutput(){
    @Override
    public void write(OutputStream output) throws IOException, WebApplicationException {
        output.write(imageBytes);
        output.flush();
    }
});