Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve dynamic generated images using restlet

I have searched online for a while and almost all the questions regarding image serving using restlet are about static images. What I want to do is to serve dynamic generated image from restlet.

I have tried serving static images using restlet, it's working. Also, I can successfully generate a dynamic image and store them in a local folder, so the problem goes to how to serving it. If it's an http response, what I shall do is to attach all the bytes of the image to the body of the response. However, I am not sure about how to use restlet to do that? Is it FileRepresentation?

Newbie in this field, and any suggestion will be welcomed.

Thanks

like image 284
Lily Avatar asked Oct 02 '09 14:10

Lily


2 Answers

I'm a little late to the party, but here is a class with which you can serve your images:

package za.co.shopfront.server.api.rest.representations;

import java.io.IOException;
import java.io.OutputStream;

import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;

public class DynamicFileRepresentation extends OutputRepresentation {

    private byte[] fileData;

    public DynamicFileRepresentation(MediaType mediaType, long expectedSize, byte[] fileData) {
        super(mediaType, expectedSize);
        this.fileData = fileData;
    }

    @Override
    public void write(OutputStream outputStream) throws IOException {
        outputStream.write(fileData);
    }

}

In the restlet handler, you can then return it like this:

@Get
public Representation getThumbnail() {

    String imageId = getRequest().getResourceRef().getQueryAsForm().getFirstValue("imageId");
    SDTO_ThumbnailData thumbnailData = CurrentSetup.PLATFORM.getImageAPI().getThumbnailDataByUrlAndImageId(getCustomerUrl(), imageId);
    return new DynamicFileRepresentation(
            MediaType.valueOf(thumbnailData.getThumbNailContentType()), 
            thumbnailData.getSize(), 
            thumbnailData.getImageData());
}

Hope this helps! :)

like image 108
Pieter Breed Avatar answered Sep 28 '22 07:09

Pieter Breed


There is an easyer way you can use ByteArrayRepresentation:

@Get
public ByteArrayRepresentation getThumbnail() {
    byte[] image = this.getImage();
    return new ByteArrayRepresentation(image , MediaType.IMAGE_PNG);
}
like image 31
patrick Avatar answered Sep 28 '22 08:09

patrick