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)
CQ5: Loading an image from a resource in a custom image renderer,
Thank for the post, David.
1.) when I am already at the jsp level (ie no custom servlet written) – how do I get a handle to the ImageContext object?
2.) I am using a pathfield object which contains the path to the object in the DAM already. ex. /content/dam/ea/someGame/background_1.jpg
I can then get the resource and then adapt it to an Asset:
Resource res = slingRequest.getResourceResolver().getResource(path);
Asset a = res.adaptTo(Asset.class);
But then how do I get the Image object (com.day.cq.wcm.foundation.Image) from that?
Thanks in advance!
Jason