0

我正在寻找从 DAM 调整图像大小,我的图像路径存储在直接链接到 DAM 资产的路径字段中。其中图像是“/content/dam/....jpg”;我可以访问 DAM 路径,我需要调整此图像的大小并使用选择器显示。我尝试了使用基础图像组件的代码,它对我不起作用。

 Resource rsc = resourceResolver.getResource(image);
                    Image img3 = new Image(rsc);

                    img3.setSrc(img3.getPath());
                    img3.setSelector(".myselector");
                    img3.setFileReference(image);

                    img3.draw(out);
4

1 回答 1

1

如果要使用选择器,则需要为其创建一个扩展 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);
}

希望有帮助。

于 2013-05-28T22:10:19.073 回答