【问题标题】:Return image in base64 from rest service to img src tag将base64中的图像从rest服务返回到img src标签
【发布时间】:2017-01-19 02:27:38
【问题描述】:

我在加载 base 64 格式的图像时遇到了一点问题。

在前端我有: <img src="/path/to/rest/image">

其余服务表示:

@GET
@PublicResource
@Produces("image/*")
@Path("/path/to/rest/image")
public Response getResource() {

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(86400);
    cacheControl.setPrivate(true);
    //image.imputStream() is the stream of the image's base64 representation
    Response.ok(image.getInputStream())).cacheControl(cacheControl)
                    .header("Cache-Control", "max-age=86400").build();
}

它返回正确的 base64,当我在任何解析器中将其解析为图像时,它会显示图像。但是 img 标签仍然显示图像已损坏。 任何想法如何解决它?可能我必须添加一些标题。

【问题讨论】:

    标签: java html image rest base64


    【解决方案1】:
    @GET
    @Path("/users/photo")
    @Produces("image/*")
    public Response getPhoto(@Context HttpServletRequest req, @QueryParam("userKey") String userKey) {
        String photo = getStaffPhoto(NullUtils.empty(userKey));
        String mime = photo.split(",")[0].split(":")[1].split(";")[0];
        byte[] data = Base64.getMimeDecoder().decode(photo.split(",")[1]);
        return Response
                .ok( data, mime )
                .build();
    }
    

    也许那段代码会有所帮助。我将照片作为字符串存储在 DB 中,看起来像“data:image/gif;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4RF....”它们由 userKey 使用 getStaffPhoto() 方法获取。

    在客户端,代码如下所示

    <script>
       var getImage = function(userKey) {
           var userPhoto = getBaseUrl() + "/users/photo?userKey=" + userKey; 
           return "<img src='"+ userPhoto + "'/>";
       }
    </script>
    

    【讨论】:

      【解决方案2】:

      将以下文本添加到从 rest 服务返回的 base 64

      data:image/png; base64, 
      

      【讨论】:

      • 图像可能是 JPEG 以外的任何其他类型。请检查
      • data:image/png;base64,iVBORw0KGgoAAAAN... 这是 png。
      • 所以改一下试试
      • 您还需要将图像的 base64 作为字符串而不是流返回。还要检查您是否在页面的 HTML 中获取 base64 字符串
      • 我尝试使用 png 和 jpeg 并返回字符串,但仍然没有。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多