Get (optional) crop dimensions from resource
@param mediaRequest Media request
@return Crop dimension or null if not set or invalid
@deprecated Use {@link #getMediaCropDimension(MediaRequest, MediaHandlerConfig)}
431021
@Deprecated
  protected final @Nullable CropDimension getMediaCropDimension(@NotNull MediaRequest mediaRequest) {
    return getMediaCropDimension(mediaRequest, null);
  }
1193733
@SuppressWarnings({ "null", "unused" })
  @NotNull
  Media processRequest(@NotNull final MediaRequest mediaRequest) {

    // detect media source
    MediaSource mediaSource = null;
    List<Class<? extends MediaSource>> mediaSources = mediaHandlerConfig.getSources();
    if (mediaSources == null || mediaSources.isEmpty()) {
      throw new RuntimeException("No media sources defined.");
    }
    MediaSource firstMediaSource = null;
    for (Class<? extends MediaSource> candidateMediaSourceClass : mediaSources) {
      MediaSource candidateMediaSource = AdaptTo.notNull(adaptable, candidateMediaSourceClass);
      if (candidateMediaSource.accepts(mediaRequest)) {
        mediaSource = candidateMediaSource;
        break;
      }
      else if (firstMediaSource == null) {
        firstMediaSource = candidateMediaSource;
      }
    }
    // if no media source was detected use first media resource defined
    if (mediaSource == null) {
      mediaSource = firstMediaSource;
    }
    Media media = new Media(mediaSource, mediaRequest);

    // resolve media format names to media formats
    MediaFormatResolver mediaFormatResolver = new MediaFormatResolver(mediaFormatHandler);
    if (!mediaFormatResolver.resolve(mediaRequest.getMediaArgs())) {
      media.setMediaInvalidReason(MediaInvalidReason.INVALID_MEDIA_FORMAT);
      return media;
    }

    // if only downloads are accepted prepare media format filter set which only contains download media formats
    if (!resolveDownloadMediaFormats(mediaRequest.getMediaArgs())) {
      media.setMediaInvalidReason(MediaInvalidReason.INVALID_MEDIA_FORMAT);
      return media;
    }

    // apply defaults to media args
    if (mediaRequest.getMediaArgs().isIncludeAssetWebRenditions() == null) {
      mediaRequest.getMediaArgs().includeAssetWebRenditions(mediaHandlerConfig.includeAssetWebRenditionsByDefault());
    }

    // preprocess media request before resolving
    List<Class<? extends MediaProcessor>> mediaPreProcessors = mediaHandlerConfig.getPreProcessors();
    if (mediaPreProcessors != null) {
      for (Class<? extends MediaProcessor> processorClass : mediaPreProcessors) {
        MediaProcessor processor = AdaptTo.notNull(adaptable, processorClass);
        media = processor.process(media);
        if (media == null) {
          throw new RuntimeException("MediaPreProcessor '" + processor + "' returned null, request: " + mediaRequest);
        }
      }
    }

    // resolve media request
    media = mediaSource.resolveMedia(media);
    if (media == null) {
      throw new RuntimeException("MediaType '" + mediaSource + "' returned null, request: " + mediaRequest);
    }

    // generate markup (if markup builder is available) - first accepting wins
    List<Class<? extends MediaMarkupBuilder>> mediaMarkupBuilders = mediaHandlerConfig.getMarkupBuilders();
    if (mediaMarkupBuilders != null) {
      for (Class<? extends MediaMarkupBuilder> mediaMarkupBuilderClass : mediaMarkupBuilders) {
        MediaMarkupBuilder mediaMarkupBuilder = AdaptTo.notNull(adaptable, mediaMarkupBuilderClass);
        if (mediaMarkupBuilder.accepts(media)) {
          media.setElement(mediaMarkupBuilder.build(media));
          break;
        }
      }
    }

    // postprocess media request after resolving
    List<Class<? extends MediaProcessor>> mediaPostProcessors = mediaHandlerConfig.getPostProcessors();
    if (mediaPostProcessors != null) {
      for (Class<? extends MediaProcessor> processorClass : mediaPostProcessors) {
        MediaProcessor processor = AdaptTo.notNull(adaptable, processorClass);
        media = processor.process(media);
        if (media == null) {
          throw new RuntimeException("MediaPostProcessor '" + processor + "' returned null, request: " + mediaRequest);
        }
      }
    }

    return media;
  }
643994
private String getSmallImageScaleParam(CmsResultItemBean infoBean) {

        String result = null;
        if (infoBean.getDimension() != null) {
            String[] sizes = infoBean.getDimension().split("x");
            try {
                int width = Integer.parseInt(sizes[0].trim());
                int height = Integer.parseInt(sizes[1].trim());
                // only use the small image dimensions in case of dimensions smaller than the big thumbnail
                if ((I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().bigImageWidth() > width)
                    || (I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().bigImageHeight() > height)) {
                    result = IMAGE_SCALE_PARAM
                        + ",w:"
                        + I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().smallImageWidth()
                        + ",h:"
                        + I_CmsLayoutBundle.INSTANCE.galleryResultItemCss().smallImageHeight();
                }
            } catch (Exception e) {
                // failed parsing the dimensions, will use big image
            }
        }
        if (result == null) {
            result = getBigImageScaleParam();
        }
        return result;
    }
1301984
protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {
        // Get crop coordinates
        int x = ServletUtil.getIntParameter(pRequest, PARAM_CROP_X, -1);
        int y = ServletUtil.getIntParameter(pRequest, PARAM_CROP_Y, -1);
        int width = ServletUtil.getIntParameter(pRequest, PARAM_CROP_WIDTH, -1);
        int height = ServletUtil.getIntParameter(pRequest, PARAM_CROP_HEIGHT, -1);

        boolean uniform =
                ServletUtil.getBooleanParameter(pRequest, PARAM_CROP_UNIFORM, false);

        int units = getUnits(ServletUtil.getParameter(pRequest, PARAM_CROP_UNITS, null));

        // Get crop bounds
        Rectangle bounds =
                getBounds(x, y, width, height, units, uniform, pImage);

        // Return cropped version
        return pImage.getSubimage((int) bounds.getX(), (int) bounds.getY(),
                                  (int) bounds.getWidth(),
                                  (int) bounds.getHeight());
        //return scaled.getSubimage(x, y, width, height);
    }
1264576
private Dimension getRequestedDimension() {

    // check for fixed dimensions from media args
    if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) {
      return new Dimension(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight());
    }

    // check for dimensions from mediaformat (evaluate only first media format)
    MediaFormat[] mediaFormats = mediaArgs.getMediaFormats();
    if (mediaFormats != null && mediaFormats.length > 0) {
      Dimension dimension = mediaFormats[0].getMinDimension();
      if (dimension != null) {
        return dimension;
      }
    }

    // fallback to 0/0 - no specific dimension requested
    return new Dimension(0, 0);
  }
360191
protected function getSelectionParams()
    {
        $result = $this->getSession('media_crop_selection_params');

        if ($result) {
            if (!isset($result['mode'])) {
                $result['mode'] = self::SELECTION_MODE_NORMAL;
            }

            if (!isset($result['width'])) {
                $result['width'] = null;
            }

            if (!isset($result['height'])) {
                $result['height'] = null;
            }

            return $result;
        }

        return [
            'mode'   => self::SELECTION_MODE_NORMAL,
            'width'  => null,
            'height' => null
        ];
    }
682530
def get_rendition_size(self, spec, output_scale, crop):
        

        if crop:
            # Use the cropping rectangle size
            _, _, width, height = crop
        else:
            # Use the original image size
            width = self._record.width
            height = self._record.height

        mode = spec.get('resize', 'fit')
        if mode == 'fit':
            return self.get_rendition_fit_size(spec, width, height, output_scale)

        if mode == 'fill':
            return self.get_rendition_fill_size(spec, width, height, output_scale)

        if mode == 'stretch':
            return self.get_rendition_stretch_size(spec, width, height, output_scale)

        raise ValueError("Unknown resize mode {}".format(mode))
246124
def get_crop_size(crop_w, crop_h, image_w, image_h):
    
    scale1 = float(crop_w) / float(image_w)
    scale2 = float(crop_h) / float(image_h)
    scale1_w = crop_w  # int(round(img_w * scale1))
    scale1_h = int(round(image_h * scale1))
    scale2_w = int(round(image_w * scale2))
    scale2_h = crop_h  # int(round(img_h * scale2))

    if scale1_h > crop_h:  # scale1_w == crop_w
        # crop on vertical
        return (scale1_w, scale1_h)
    else:  # scale2_h == crop_h and scale2_w > crop_w
        #crop on horizontal
        return (scale2_w, scale2_h)
1309516
private function getCropRectangle($image, $targetBox, $horzMode, $vertMode)
	{
		$imageBox = $image->getSize();
		$kw = $imageBox->getWidth() / $targetBox->getWidth();
		$kh = $imageBox->getHeight() / $targetBox->getHeight();
		$x = $y = $w = $h = 0;
		if($kh > $kw) {
			$x = 0;
			$w = $imageBox->getWidth();
			$h = $targetBox->getHeight() * $kw;
			switch ($vertMode) {
				case self::CROP_TOP:
					$y = 0;
					break;
				case self::CROP_BOTTOM:
					$y = $imageBox->getHeight() - $h;
					break;
				case self::CROP_CENTER:
					$y = ($imageBox->getHeight() - $h) / 2;
					break;
			}
		} else {
			$y = 0;
			$h = $imageBox->getHeight();
			$w  = $targetBox->getWidth() * $kh;
			switch ($horzMode) {
				case self::CROP_LEFT:
					$x = 0;
					break;
				case self::CROP_RIGHT:
					$x = $imageBox->getWidth() - $w;
					break;
				case self::CROP_CENTER:
					$x = ($imageBox->getWidth() - $w) / 2;
					break;
			}
		}
		return [$x, $y, $w, $h];
	}
1001492
protected static MediaType getSupportProduceMediaType(ContainerRequestContext containerRequestContext) {
        for (MediaType mediaType : containerRequestContext.getAcceptableMediaTypes()) {
            if (mediaType.isCompatible(TEXT_PLAIN_TYPE) ||
                    (mediaType.getType().equalsIgnoreCase("application")
                            && !mediaType.getSubtype().toLowerCase().contains("html"))
                    || mediaType.getSubtype().equalsIgnoreCase("json")
                    || mediaType.getSubtype().equalsIgnoreCase("xml")
                    || mediaType.getSubtype().toLowerCase().endsWith("+json")
                    || mediaType.getSubtype().toLowerCase().endsWith("+xml")) {
                return mediaType;
            }
        }
        return null;
    }
217742
public function getCropDimensions() {
		$x = $this->getCropX();
		$y = $this->getCropY();
		$cropWidth = $this->getCropWidth();
		$cropHeight = $this->getCropHeight();
		$width = $cropWidth;
		$height = $cropHeight;

		// Normalise the width/height with respect to the aspect ratio
		$maxWidth = $this->getMaxWidth();
		$maxHeight = $this->getMaxHeight();

		$aspectRatio = $this->getAspectRatio();


		if($width < 1 || $height < 1) {
			throw new \InvalidArgumentException('Values must be over 1');
		}

		// Fix the aspect ratio if the crop is wrong
		// This must happen first so invalid values can be compensated for
		if($width / $height != $aspectRatio) {
			$height = $width / $aspectRatio;
		}

		if($width > $maxWidth) {
			$scaleDownRatio = $cropWidth / $maxWidth;
			$height = $height / $scaleDownRatio;
			$width = $maxWidth;
		}

		if($height > $maxHeight) {
			$scaleDownRatio = $cropHeight / $maxHeight;
			$width = $width / $scaleDownRatio;
			$height = $maxHeight;
		}

		return array(
			// src_x, src_y
			'x' => $x,
			'y' => $y,
			// dst_w, dst_h
			'width' => ceil($width),
			'height' => ceil($height),
			// src_w, src_h
			'crop_width' => $cropWidth,
			'crop_height' => $cropHeight,
		);
	}
1305764
public function getPublicImage(string $size, string $cropType) : string
    {
        $size = strtolower($size);
        $cropType = strtolower($cropType);

        list ($width, $height) = explode('x', $size);

        $width = $width === 'null' ? NULL : $width;
        $height = $height === 'null' ? NULL : $height;

        if (!$width && !$height)
        {
            throw new InvalidArgumentException("One of this parameters: 'size-width' or 'size-height' is required.");
        }

        if (!in_array($cropType, self::CROP_TYPES))
        {
            $allowedArguments = implode(', ', self::CROP_TYPES);
            throw new InvalidArgumentException("Argument \$cropType '{$cropType}' is invalid. Allowed arguments are '{$allowedArguments}'");
        }

        $privateFile = $this->getPrivateFile();

        if ($privateFile)
        {
            $name = basename($privateFile->getFilename(), '.' . $privateFile->getExtension());
            $name .= "---{$width}x{$height}-{$cropType}." . $privateFile->getExtension();
        }
        else
        {
            $this->destination = 'no-image/';
            $name = "no-image---{$width}x{$height}-{$cropType}.jpg";
        }

        $publicFilePath = self::PUBLIC_ABSOLUTE_PATH . $this->destination;

        if (!file_exists($publicFilePath . $name))
        {
            if (!is_dir($publicFilePath))
            {
                FileSystem::createDir($publicFilePath);
            }

            if ($privateFile)
            {
                $image = Image::fromFile($privateFile->getPathname());
            }
            else
            {
                $width = (!$width) ? $height / 2 : $width;
                $height = (!$height) ? $width / 2 : $height;
                $image = Image::fromBlank($width, $height, Image::rgb(204,204,204));
            }

            $image->resize($width, $height, array_search($cropType, self::CROP_TYPES));
            $image->save($publicFilePath . $name, self::IMAGE_QUALITY);
        }

        return  self::PUBLIC_RELATIVE_PATH . $this->destination . $name;
    }
399388
public GetMediaSourceDownloadResponse getMediaSourceDownload(GetMediaSourceDownloadRequest request) {

        checkStringNotEmpty(request.getMediaId(), "Media ID should not be null or empty!");

        InternalRequest internalRequest =
                createRequest(HttpMethodName.GET, request, PATH_MEDIA, request.getMediaId());
        internalRequest.addParameter(PARA_DOWNLOAD, null);
        internalRequest.addParameter(PARA_EXPIREDINSECONDS, String.valueOf(request.getExpiredInSeconds()));

        return invokeHttpClient(internalRequest, GetMediaSourceDownloadResponse.class);
    }
488534
@SuppressWarnings("resource")
    public String getDimensions() {

        try {
            BufferedImage img = Simapi.read(IOUtils.toByteArray(new FileInputStream(m_variationPath)));
            return "" + img.getWidth() + " x " + img.getHeight() + "px";
        } catch (IOException e) {
            return "";
        }
    }
466283
public static Dimension getDimension(File videoFile) throws IOException {
    try (FileInputStream fis = new FileInputStream(videoFile)) {
      return getDimension(fis, new AtomicReference<ByteBuffer>());
    }
  }
535589
private String buildMediaUrl(Dimension scaledDimension) {

    // check for file extension filtering
    if (!isMatchingFileExtension()) {
      return null;
    }

    // check if image has to be rescaled
    if (scaledDimension != null) {

      // check if scaling is not possible
      if (scaledDimension.equals(SCALING_NOT_POSSIBLE_DIMENSION)) {
        return null;
      }

      // otherwise generate scaled image URL
      return buildScaledMediaUrl(scaledDimension, this.media.getCropDimension());
    }

    // if no scaling but cropping required builid scaled image URL
    if (this.media.getCropDimension() != null) {
      return buildScaledMediaUrl(this.media.getCropDimension(), this.media.getCropDimension());
    }

    if (mediaArgs.isContentDispositionAttachment()) {
      // if not scaling and no cropping required but special content disposition headers required build download url
      return buildDownloadMediaUrl();
    }
    else {
      // if not scaling and no cropping required build native media URL
      return buildNativeMediaUrl();
    }
  }
1145800
@SuppressWarnings("null")
  protected final @Nullable Integer getMediaRotation(@NotNull MediaRequest mediaRequest,
      @NotNull MediaHandlerConfig mediaHandlerConfig) {
    if (mediaRequest.getResource() != null) {
      String rotationProperty = getMediaRotationProperty(mediaRequest, mediaHandlerConfig);
      String stringValue = mediaRequest.getResource().getValueMap().get(rotationProperty, String.class);
      if (StringUtils.isNotEmpty(stringValue)) {
        int rotationValue = NumberUtils.toInt(stringValue);
        if (TransformedRenditionHandler.isValidRotation(rotationValue)) {
          return rotationValue;
        }
      }
    }
    return null;
  }