如果要使用选择器,则需要为其创建一个扩展 AbstractImageServlet 的 servlet。你会从这样的事情开始:
@Component
@Service
@Properties({
@Property(name="sling.servlet.resourceTypes", value="sling/servlet/default"),
@Property(name="sling.servlet.selectors", value="resize"),
@Property(name="sling.servlet.extensions", value={"jpg", "png", "gif"}),
@Property(name="sling.servlet.methods", value="GET")
})
public class ImageResizeServlet extends AbstractImageServlet {
//... code.
}
sling.servlet.selectors 将是您要设置的选择器名称。例如:
//in the servlet
@Property(name="sling.servlet.selectors", value="resize")
//in the jsp
image.setSelector("resize");
在您的类中,您可能希望覆盖 writeLayer 方法。像这样的东西:
@Override
protected void writeLayer(SlingHttpServletRequest req,
SlingHttpServletResponse resp,
AbstractImageServlet.ImageContext c, Layer layer)
throws IOException, RepositoryException {
// set new width and height
int width = 100;
int height = 100;
Image image = new Image(c.resource);
if (!image.hasContent() || width == 0) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// get style and set constraints
image.loadStyleData(c.style);
// get pure layer
layer = image.getLayer(true, true, true);
Layer newLayer = ImageHelper.resize(layer, new Dimension(width, 0), null, null);
if (newLayer != null) {
layer = newLayer;
}
String mimeType = image.getMimeType();
if (ImageHelper.getExtensionFromType(mimeType) == null) {
// get default mime type
mimeType = "image/png";
}
resp.setContentType(mimeType);
layer.write(mimeType, mimeType.equals("image/gif") ? 255 : 1.0, resp.getOutputStream());
resp.flushBuffer();
}
在我们的自定义解决方案中,我们在 writeLayer 方法而不是 createLayer 方法中处理所有内容。所以我们覆盖了createLayer。
@Override
protected Layer createLayer(AbstractImageServlet.ImageContext c)
throws RepositoryException, IOException {
// don't create the layer yet. handle everything later
return null;
}
我们还覆盖了 createImageResource
/**
* {@inheritDoc}
*
* Override default ImageResource creation to support assets
*/
@Override
protected ImageResource createImageResource(Resource resource) {
return new Image(resource);
}
希望有帮助。