要在AEM 6.5中的Sites目录中显示缩略图,你可以使用以下代码示例来解决问题:
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@Component(service = Servlet.class)
@SlingServletResourceTypes(
resourceTypes = "sling/servlet/default",
selectors = "thumbnail",
extensions = "jpg",
methods = "GET"
)
public class ThumbnailServlet extends SlingSafeMethodsServlet {
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
// 获取图片资源路径
String imagePath = request.getParameter("path");
ResourceResolver resourceResolver = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
// 获取ResourceResolver
resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
Resource imageResource = resourceResolver.getResource(imagePath);
if (imageResource != null) {
// 读取原始图片
inputStream = imageResource.adaptTo(InputStream.class);
BufferedImage image = ImageIO.read(inputStream);
if (image != null) {
// 生成缩略图
BufferedImage thumbnail = Scalr.resize(image, 100);
// 设置响应类型为JPEG
response.setContentType("image/jpeg");
// 将缩略图输出到响应流
outputStream = response.getOutputStream();
ImageIO.write(thumbnail, "jpeg", outputStream);
}
}
} catch (Exception e) {
// 处理异常
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} finally {
// 关闭流和释放资源
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
}
现在,当你在Sites目录中访问图片资源时,可以使用以下URL来获取缩略图:
/sites.html/content/dam/path/to/image.thumbnail.jpg
请替换path/to/image
为实际的图片资源路径。你可以在浏览器中访问此URL以获取生成的缩略图。