Serve dynamic generated images using restlet
Question
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
Solution
FileRepresentation should work if you write the image to a file first. For a more efficient approach, you can create your own Representation class by extending OutputRepresentation and overriding the write(OutputStream)
method.
OTHER TIPS
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! :)
There is an easyer way you can use ByteArrayRepresentation:
@Get
public ByteArrayRepresentation getThumbnail() {
byte[] image = this.getImage();
return new ByteArrayRepresentation(image , MediaType.IMAGE_PNG);
}