CQ5: Loading an image from a resource in a custom image renderer

Issue

If you are using a custom image renderer to handle image renders, you may notice that you cannot create a valid Image object from a referenced Asset in the DAM.  You are probably using code similar to the following:

//Note c is an ImageContext object
Resource r = c.request.getResourceResolver().getResource("/content/dam/geometrixx/travel/train_station_woman.jpg");
Image i = new Image(r);
if (!i.hasContent()) {
    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
}

In the example code snippet above, hasContent() will always return false.

Reason

You cannot simply create an image or a layer directly from an image/file resource as obtained from the resolver.  You must first use the Asset class to get a rendition of the image.  Then you can work with that.

Solution

Use code similar to the following

//Note c is an ImageContext object
Resource  r = c.request.getResourceResolver().getResource("/content/dam/geometrixx/travel/train_station_woman.jpg");
Asset a = r.adaptTo(Asset.class);
Layer layer = ImageHelper.createLayer(
      c.node.getSession(),
      a.getCurrentOriginal().getPath()
)

reference: (36895)

VN:F [1.9.22_1171]
Was this helpful? Please rate the content.
Rating: 5.0/10 (5 votes cast)