如何在Jersey REST服务方法中返回PNG图像到浏览器

61
我有一个运行着Jersey REST资源的Web服务器,想知道如何获取一个 image/png 的引用以便在提交表单或接收Ajax响应后在浏览器中使用img标签。添加图形的图像处理代码已经可以工作了,只需要想办法返回它即可。
代码:
@POST
@Path("{fullsize}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("image/png")
// Would need to replace void
public void getFullImage(@FormDataParam("photo") InputStream imageIS,
                         @FormDataParam("submit") String extra) {

      BufferedImage image = ImageIO.read(imageIS);

      // .... image processing
      //.... image processing

      return ImageIO.  ..  ?

}

干杯


你想要实现什么?你不能通过发送一个带有图片位置的URI来实现吗? - Perception
我希望用户在下订单之前能够预览所选图形放置在照片上。我现在看到这无法使用 AJAX 提交完成,需要像你说的那样请求指向已处理图像的网页。 - gorn
4个回答

109

我不太认为在REST服务中返回图像数据是一个好主意。这会占用应用服务器的内存和IO带宽。更好的做法是将此任务委托给专门针对这种传输进行优化的正确的Web服务器。您可以通过发送指向图像资源的重定向(作为HTTP 302响应,并包含图像的URI)来实现此目标。当然,这假设您的图像是作为Web内容排列的。

话虽如此,如果您决定真的需要从Web服务传输图像数据,可以使用以下(伪)代码:

@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {

    BufferedImage image = ...;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] imageData = baos.toByteArray();

    // uncomment line below to send non-streamed
    // return Response.ok(imageData).build();

    // uncomment line below to send streamed
    // return Response.ok(new ByteArrayInputStream(imageData)).build();
}

添加异常处理等等。


谢谢!那是一种方法。 - gorn
最终得到了一个PHP服务器应用程序,它使用cURL从这个RESTful Java Web服务获取图像,并在HTML图像标签中指向它们。 - gorn
@gorn,你应该在你的回答中编辑并写下你的解决方案。 - kommradHomer
11
如果你能够在开头段落所建议的基础上提供代码完成你的回答,那将是非常好的,如果有人(比如我 呵呵)被你的论点所说服,这将非常有用。请补充完整你的回答并提供相应的代码示例。 - arg20
为了降低带宽,您可以在响应中添加CacheControl:CacheControll cc = new CacheControl(); cc.setMaxAge(number); Response(..).cacheControl(cc).build(); - Marcel
也许BalusC的这个答案可以帮助到其他人,它与开头段落有关: https://dev59.com/ZW855IYBdhLWcg3wFALy - edeesan

14

我创建了一个通用方法,具有以下功能:

  • 如果文件在本地没有被修改,则返回“未修改”,将 Status.NOT_MODIFIED 发送给调用方。使用 Apache Commons Lang
  • 使用文件流对象而不是读取文件本身

代码如下:

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger logger = LoggerFactory.getLogger(Utils.class);

@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
    File repositoryFile = new File("c:/temp/myfile.png");
    return returnFile(repositoryFile, modified);
}

/**
 * 
 * Sends the file if modified and "not modified" if not modified
 * future work may put each file with a unique id in a separate folder in tomcat
 *   * use that static URL for each file
 *   * if file is modified, URL of file changes
 *   * -> client always fetches correct file 
 * 
 *     method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
 * 
 * @param file to send
 * @param modified - HeaderField "If-Modified-Since" - may be "null"
 * @return Response to be sent to the client
 */
public static Response returnFile(File file, String modified) {
    if (!file.exists()) {
        return Response.status(Status.NOT_FOUND).build();
    }

    // do we really need to send the file or can send "not modified"?
    if (modified != null) {
        Date modifiedDate = null;

        // we have to switch the locale to ENGLISH as parseDate parses in the default locale
        Locale old = Locale.getDefault();
        Locale.setDefault(Locale.ENGLISH);
        try {
            modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        Locale.setDefault(old);

        if (modifiedDate != null) {
            // modifiedDate does not carry milliseconds, but fileDate does
            // therefore we have to do a range-based comparison
            // 1000 milliseconds = 1 second
            if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
                return Response.status(Status.NOT_MODIFIED).build();
            }
        }
    }        
    // we really need to send the file

    try {
        Date fileDate = new Date(file.lastModified());
        return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
    } catch (FileNotFoundException e) {
        return Response.status(Status.NOT_FOUND).build();
    }
}

/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/

/**
 * Date format pattern used to parse HTTP date headers in RFC 1123 format.
 */
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in RFC 1036 format.
 */
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";

/**
 * Date format pattern used to parse HTTP date headers in ANSI C
 * <code>asctime()</code> format.
 */
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";

public static final String[] DEFAULT_PATTERNS = new String[] {
    PATTERN_RFC1036,
    PATTERN_RFC1123,
    PATTERN_ASCTIME
};

请注意,区域设置的切换似乎不是线程安全的。我认为最好在全局范围内切换语言环境。不过,我不确定会产生什么副作用...


4
你可以使用Jersey的Request.evaluatePreconditions(...)方法来删除大量的最后修改逻辑,因为它将处理日期的解析和检查,以及如果你支持的话还会处理ETags。 - bramp

8
如果你有许多图像资源方法,那么创建一个MessageBodyWriter来输出BufferedImage是非常值得的。
@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  @Override
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;
  }

  @Override
  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2
  }

  @Override
  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);
  } 
}

如果启用了Jersey的自动发现功能,则将自动使用此MessageBodyWriter,否则需要通过自定义Application子类返回它。有关更多信息,请参见JAX-RS实体提供程序
设置完成后,只需从资源方法返回BufferedImage,它将被输出为图像文件数据:
@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();
}

这种方法有几个优点:
  • 它将内容写入响应的OutputSteam而不是中间的BufferedOutputStream
  • 它支持pngjpg输出(取决于资源方法允许的媒体类型)

8

关于@Perception的回答,当使用字节数组时会占用很多内存空间,但你也可以直接写入输出流中。

@Path("/picture")
public class ProfilePicture {
  @GET
  @Path("/thumbnail")
  @Produces("image/png")
  public StreamingOutput getThumbNail() {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException, WebApplicationException {
        //... read your stream and write into os
      }
    };
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接