ImageFileServlet.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2014 wcm.io
  6.  * %%
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  * #L%
  19.  */
  20. package io.wcm.handler.media.impl;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.IOException;

  23. import javax.servlet.Servlet;

  24. import org.apache.commons.lang3.StringUtils;
  25. import org.apache.sling.api.SlingHttpServletRequest;
  26. import org.apache.sling.api.resource.Resource;
  27. import org.apache.sling.api.servlets.HttpConstants;
  28. import org.jetbrains.annotations.NotNull;
  29. import org.jetbrains.annotations.Nullable;
  30. import org.osgi.service.component.annotations.Component;
  31. import org.osgi.service.component.annotations.Reference;

  32. import com.day.cq.commons.jcr.JcrConstants;
  33. import com.day.cq.dam.api.handler.store.AssetStore;
  34. import com.day.image.Layer;

  35. import io.wcm.handler.media.CropDimension;
  36. import io.wcm.handler.media.format.Ratio;
  37. import io.wcm.handler.media.spi.MediaHandlerConfig;
  38. import io.wcm.sling.commons.adapter.AdaptTo;
  39. import io.wcm.wcm.commons.contenttype.ContentType;
  40. import io.wcm.wcm.commons.contenttype.FileExtension;

  41. /**
  42.  * Stream resized or cropped image from binary data stored in a nt:file or nt:resource node.
  43.  * Optional support for Content-Disposition header ("download_attachment").
  44.  */
  45. @Component(service = Servlet.class, immediate = true, property = {
  46.     "sling.servlet.extensions=" + MediaFileServletConstants.EXTENSION,
  47.     "sling.servlet.selectors=" + ImageFileServlet.SELECTOR,
  48.     "sling.servlet.resourceTypes=" + JcrConstants.NT_FILE,
  49.     "sling.servlet.resourceTypes=" + JcrConstants.NT_RESOURCE,
  50.     "sling.servlet.methods=" + HttpConstants.METHOD_GET
  51. })
  52. public final class ImageFileServlet extends AbstractMediaFileServlet {
  53.   private static final long serialVersionUID = 1L;

  54.   /**
  55.    * Selector
  56.    */
  57.   public static final String SELECTOR = "image_file";

  58.   @Reference
  59.   private AssetStore assetStore;

  60.   @Override
  61.   @SuppressWarnings("java:S3776") // ignore complexity
  62.   protected byte @Nullable [] getBinaryData(@NotNull Resource resource, @NotNull SlingHttpServletRequest request) throws IOException {
  63.     // get media app config
  64.     MediaHandlerConfig config = AdaptTo.notNull(request, MediaHandlerConfig.class);

  65.     // parse selectors
  66.     ImageFileServletSelector params = new ImageFileServletSelector(request.getRequestPathInfo().getSelectors());
  67.     int width = params.getWidth();
  68.     int height = params.getHeight();
  69.     CropDimension cropDimension = params.getCropDimension();
  70.     int rotation = params.getRotation();
  71.     int quality = params.getQuality();

  72.     // ensure valid image size
  73.     if (width < 0 || height < 0 || (width == 0 && height == 0)) {
  74.       return null;
  75.     }

  76.     Layer layer = ResourceLayerUtil.toLayer(resource, assetStore);
  77.     if (layer == null) {
  78.       return null;
  79.     }

  80.     // if only width or only height is given - derive other value from ratio
  81.     double originalRatio;
  82.     if (cropDimension != null) {
  83.       originalRatio = Ratio.get(cropDimension);
  84.     }
  85.     else {
  86.       originalRatio = Ratio.get(layer.getWidth(), layer.getHeight());
  87.     }
  88.     if (width == 0) {
  89.       width = (int)Math.round(height * originalRatio);
  90.     }
  91.     else if (height == 0) {
  92.       height = (int)Math.round(width / originalRatio);
  93.     }

  94.     // if required: crop image
  95.     if (cropDimension != null) {
  96.       layer.crop(cropDimension.getRectangle());
  97.     }
  98.     else {
  99.       // if image ratio that is requested does not match with the given ratio apply a center-crop here
  100.       double requestedRatio = Ratio.get(width, height);
  101.       if (!Ratio.matches(originalRatio, requestedRatio)) {
  102.         cropDimension = ImageTransformation.calculateAutoCropDimension(layer.getWidth(), layer.getHeight(), requestedRatio);
  103.         layer.crop(cropDimension.getRectangle());
  104.       }
  105.     }

  106.     // if required: rotate image
  107.     if (rotation != 0) {
  108.       layer.rotate(rotation);
  109.     }

  110.     // resize layer
  111.     if (width <= layer.getWidth() && height <= layer.getHeight()) {
  112.       layer.resize(width, height);
  113.     }

  114.     // determine layer quality with fallback to default image quality if not set
  115.     String contentType = getContentType(resource, request);
  116.     double layerQuality;
  117.     if (quality > 0) {
  118.       layerQuality = quality / 100d;
  119.     }
  120.     else {
  121.       layerQuality = config.getDefaultImageQuality(contentType);
  122.     }

  123.     // stream to byte array
  124.     ByteArrayOutputStream bos = new ByteArrayOutputStream();
  125.     layer.write(contentType, layerQuality, bos);
  126.     bos.flush();
  127.     return bos.toByteArray();
  128.   }

  129.   @Override
  130.   protected @NotNull String getContentType(@NotNull Resource resource, @NotNull SlingHttpServletRequest request) {

  131.     // get filename from suffix to get extension
  132.     String fileName = request.getRequestPathInfo().getSuffix();
  133.     if (StringUtils.isNotEmpty(fileName)) {
  134.       // if extension is PNG use PNG content type, otherwise fallback to JPEG
  135.       String fileExtension = StringUtils.substringAfterLast(fileName, ".");
  136.       if (StringUtils.equalsIgnoreCase(fileExtension, FileExtension.PNG)) {
  137.         return ContentType.PNG;
  138.       }
  139.     }

  140.     // for rendered images use JPEG mime type as default fallback
  141.     return ContentType.JPEG;
  142.   }

  143.   /**
  144.    * Get image filename to be used for the URL with file extension matching the image format which is produced by this
  145.    * servlet.
  146.    * @param originalFilename Original filename of the image to render.
  147.    * @return Filename to be used for URL.
  148.    */
  149.   public static String getImageFileName(@NotNull String originalFilename) {
  150.     return getImageFileName(originalFilename, null);
  151.   }

  152.   /**
  153.    * Get image filename to be used for the URL with file extension matching the image format which is produced by this
  154.    * servlet.
  155.    * @param originalFilename Original filename of the image to render.
  156.    * @param enforceOutputFileExtension Enforced output file extensions from media args
  157.    * @return Filename to be used for URL.
  158.    */
  159.   public static String getImageFileName(@NotNull String originalFilename,
  160.       @Nullable String enforceOutputFileExtension) {
  161.     String namePart = StringUtils.substringBeforeLast(originalFilename, ".");
  162.     String extensionPart = StringUtils.substringAfterLast(originalFilename, ".");
  163.     if (enforceOutputFileExtension != null) {
  164.       extensionPart = enforceOutputFileExtension;
  165.     }

  166.     // use PNG format if requested format is PNG, otherwise always use JPEG
  167.     if (StringUtils.equalsIgnoreCase(extensionPart, FileExtension.PNG)) {
  168.       extensionPart = FileExtension.PNG;
  169.     }
  170.     else {
  171.       extensionPart = FileExtension.JPEG;
  172.     }
  173.     return namePart + "." + extensionPart;
  174.   }

  175. }