使用restlet提供动态生成的图像

Lil*_*ily 7 java image dynamic restlet

我在网上搜索了一段时间,几乎所有关于使用restlet提供图像的问题都是静态图像.我想要做的是从restlet提供动态生成的图像.

我尝试使用restlet提供静态图像,它正在工作.此外,我可以成功生成动态图像并将其存储在本地文件夹中,因此问题在于如何提供它.如果它是一个http响应,我要做的是将图像的所有字节附加到响应的主体.但是,我不确定如何使用restlet来做到这一点?是FileRepresentation吗?

这个领域的新手,任何建议都将受到欢迎.

谢谢

Pie*_*eed 5

我参加派对的时间有点晚了,但是这里有一个可以为你提供图像的课程:

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

}
Run Code Online (Sandbox Code Playgroud)

在restlet处理程序中,您可以像这样返回它:

@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());
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!:)


小智 0

如果您首先将图像写入文件,FileRepresentation 应该可以工作。为了获得更有效的方法,您可以通过扩展 OutputRepresentation 并重写该write(OutputStream)方法来创建自己的 Representation 类。