InlineAutoCropping.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2019 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.mediasource.inline;

  21. import java.util.Arrays;
  22. import java.util.List;
  23. import java.util.Objects;
  24. import java.util.stream.Collectors;
  25. import java.util.stream.Stream;

  26. import org.apache.commons.lang3.ObjectUtils;
  27. import org.jetbrains.annotations.NotNull;

  28. import io.wcm.handler.media.CropDimension;
  29. import io.wcm.handler.media.Dimension;
  30. import io.wcm.handler.media.MediaArgs;
  31. import io.wcm.handler.media.format.MediaFormat;
  32. import io.wcm.handler.media.impl.ImageTransformation;

  33. /**
  34.  * Helper class for calculating crop dimensions for auto-cropping.
  35.  */
  36. class InlineAutoCropping {

  37.   private final Dimension imageDimension;
  38.   private final MediaArgs mediaArgs;

  39.   InlineAutoCropping(@NotNull Dimension imageDimension, @NotNull MediaArgs mediaArgs) {
  40.     this.imageDimension = imageDimension;
  41.     this.mediaArgs = mediaArgs;
  42.   }

  43.   public List<CropDimension> calculateAutoCropDimensions() {
  44.     Stream<MediaFormat> mediaFormats = Arrays.stream(
  45.         ObjectUtils.defaultIfNull(mediaArgs.getMediaFormats(), new MediaFormat[0]));
  46.     return mediaFormats
  47.         .map(this::calculateAutoCropDimension)
  48.         .filter(Objects::nonNull)
  49.         .collect(Collectors.toList());
  50.   }

  51.   private CropDimension calculateAutoCropDimension(@NotNull MediaFormat mediaFormat) {
  52.     double ratio = mediaFormat.getRatio();
  53.     if (ratio > 0 && imageDimension.getWidth() > 0 && imageDimension.getHeight() > 0) {
  54.       return ImageTransformation.calculateAutoCropDimension(imageDimension.getWidth(), imageDimension.getHeight(), ratio);
  55.     }
  56.     return null;
  57.   }

  58. }