user3568791
user3568791

Reputation: 716

Return image in base64 from rest service to img src tag

I have a little problem with loading an image in base 64 format.

In the frontend I have: <img src="/path/to/rest/image">

The rest service represents:

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

It returns correct base64 and when I parse it to image in any parser it shows the image. But the img tag still shows that the image is broken. Any ideas how to fix it ? Probably I have to add some headers.

Upvotes: 2

Views: 6122

Answers (2)

karagota
karagota

Reputation: 53

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

Maybe that piece of code will help a bit. I store photos in DB as Strings which look like "data:image/gif;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4RF...." They are fetched by userKey with getStaffPhoto() method.

On the client side the code looks like

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

Upvotes: 0

Akshey Bhat
Akshey Bhat

Reputation: 8545

Prepend the following text to base 64 returned from rest service

data:image/png; base64, 

Upvotes: 1

Related Questions