I want to display 'cq5dam.thumbnail.140.100.png' rendition of my image asset as a thumbnail in my html page. How can I get the asset path of one of my asset in DAM in a java/JSP for a given rendition
Asked
Active
Viewed 1,549 times
1 Answers
0
this function will do the trick
public static String getImageAssetPath(SlingHttpServletRequest slingRequest,String actualDamPath,String renditionParam,String defaultPath) {
try {
if(StringUtils.isNotEmpty(actualPath)){
Resource resource = slingRequest.getResourceResolver().getResource(actualPath);
Asset asset = resource.adaptTo(Asset.class);
String imageAssetPath = asset.getRendition(renditionParam).getPath();
LOGGER.info("imageAssetPath for given rendition: " + imageAssetPath);
return imageAssetPath;
}
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return defaultPath;
}
put this function in a tag library so that the same can be used in your jsps
${mytaglib:getAssetPath(slingRequest,property.previewImage,'cq5dam.thumbnail.140.100.png','')}

ShAkKiR
- 863
- 9
- 20
-
1Just because a lot of people just copy and paste code from SO. This code contains at least three possible `NullPointerExceptions`. `getResource()` might return `null` if there is no resource at this path. `adaptTo` will (silently) return `null` if the given resource is not an asset and `getRendition()` will also return `null` if the asset has no rendition with that exact name. – Jens May 16 '18 at 20:45
-
in all these cases it will return defaultPath right! – ShAkKiR May 17 '18 at 06:20
-
That is true but just catching `Exception` is considered bad practice and I bet your Sonar (or whatever code quality tool you are using at your company) would complain as well. Why not write code with minimal chance of creating exceptions in the first place? Anyway. The point is that I wanted to tell people that they should not just copy this piece of code blindly but be aware of the possible NPE. – Jens May 17 '18 at 10:11
-
Got it Jen, Thanks, It was not meant to be a production ready code :p – ShAkKiR May 17 '18 at 11:28