RelativeCroppingString.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2024 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.dam.impl.weboptimized;

  21. import java.text.DecimalFormat;
  22. import java.text.DecimalFormatSymbols;
  23. import java.text.NumberFormat;
  24. import java.util.Locale;

  25. import org.jetbrains.annotations.NotNull;

  26. import io.wcm.handler.media.CropDimension;
  27. import io.wcm.handler.media.Dimension;

  28. /**
  29.  * Creates relative crop string with percentage values as required by the Web-Optimized Image Delivery API.
  30.  * It uses one fractional digit for the percentage values.
  31.  */
  32. final class RelativeCroppingString {

  33.   private static final NumberFormat DECIMAL_FORMAT = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US));

  34.   private RelativeCroppingString() {
  35.     // static methods only
  36.   }

  37.   static @NotNull String createFromCropDimension(
  38.       @NotNull CropDimension cropDimension, @NotNull Dimension imageDimension) {
  39.     double x1 = cropDimension.getLeft();
  40.     double y1 = cropDimension.getTop();
  41.     double left = x1 / imageDimension.getWidth();
  42.     double top = y1 / imageDimension.getHeight();
  43.     double width = (double)cropDimension.getWidth() / imageDimension.getWidth();
  44.     double height = (double)cropDimension.getHeight() / imageDimension.getHeight();
  45.     return create(left, top, width, height);
  46.   }

  47.   static @NotNull String create(double left, double top, double width, double height) {
  48.     return String.format("%sp,%sp,%sp,%sp",
  49.         toPercentage(left), toPercentage(top),
  50.         toPercentage(width), toPercentage(height));
  51.   }

  52.   private static String toPercentage(double fraction) {
  53.     double percentage = Math.round(fraction * 1000d) / 10d;
  54.     percentage = Math.max(0.0, percentage);
  55.     percentage = Math.min(100.0, percentage);
  56.     return DECIMAL_FORMAT.format(percentage);
  57.   }

  58. }