Crop the image to the given size and aspèect ration, ignoring upsize or aspect ratio constraints

@return
546998
protected function buildImageCrop () {
    $image = Image::make($this->upload_path . $this->file_name)->orientate();

    if ($this->preset->width == 0) {
      $image->heighten($this->preset->height);
    }
    else if ($this->preset->height == 0) {
      $image->widen($this->preset->width);
    }
    else {
      $image->fit($this->preset->width, $this->preset->height);
    }

    return $image;
  }
60827
private Dimension getImageDimension() {
    Dimension dimension = null;

    // check for cropping dimension
    if (this.media.getCropDimension() != null) {
      dimension = this.media.getCropDimension();
    }
    else {
      // if binary is image try to calculcate dimensions by loading it into a layer
      Layer layer = this.resource.adaptTo(Layer.class);
      if (layer != null) {
        dimension = new Dimension(layer.getWidth(), layer.getHeight());
      }
    }

    return dimension;
  }
855836
public function crop($width, $height) {

        // GdThumb will not enforce the requested aspect ratio if the image is too
        // small, so we manually calculate what the size should be if the aspect
        // ratio is preserved.
        $options = $this->thumb->getOptions();
        if (empty($options['resizeUp'])) {
            $size = $this->thumb->getCurrentDimensions();
            $ratio = $width / $height;
            if ($size['width'] < $width) {
                $width = $size['width'];
                $height = $size['width'] / $ratio;
            }
            if ($size['height'] < $height) {
                $height = $size['height'];
                $width = $size['height'] * $ratio;
            }
        }

        // Do a normal adpative resize
        $this->thumb->adaptiveResize($width, $height);
        return $this;
    }
1197645
function(size, callback) {
      var ratio = size.width / size.height;
      var cropPosition = {};
      var resizeWidth = width || Math.round(height * ratio);
      var resizeHeight = height || Math.round(width / ratio);

      if (crop && width && height) {
        if (ratio < width / height) {
          resizeHeight = Math.round(width / ratio);
          cropPosition = {x: 0, y: Math.round((resizeHeight - height) / 2)};
          crop = resizeHeight > height;
        } else {
          resizeWidth = Math.round(height * ratio);
          cropPosition = {x: Math.round((resizeWidth - width) / 2), y: 0};
          crop = resizeWidth > width;
        }
      }

      image
        .noProfile()
        .quality(quality)
        .resizeExact(resizeWidth, resizeHeight);

      if (crop)
        image.crop(width, height, cropPosition.x, cropPosition.y);

      image.write(thumbnailPath, callback);
    }
135836
function cropImage( $imageObject, $filterData, &$filterVariables, $sourceMimeData, $destinationMimeData )
    {
        $width = $filterData['data'][0];
        $height = $filterData['data'][1];
        $x = $filterData['data'][2];
        $y = $filterData['data'][3];
        $imageWidth = ImageSX( $imageObject );
        $imageHeight = ImageSY( $imageObject );
        $width = max( min( $width, $imageWidth - $x ), 0 );
        $height = max( min( $height, $imageHeight - $y ), 0 );
        $destinationGeometry = $this->createGeometry( $width, $height, 0, 0 );
        $geometry = $this->createGeometry( $width, $height, $x, $y );
        return $this->imageCopy( $imageObject,
                                 $destinationGeometry,
                                 $geometry,
                                 $sourceMimeData, $destinationMimeData );
    }
1238950
def crop_image(img, padding=5):
    ""

    if padding < 1:
        return img

    beg_coords, end_coords = crop_coords(img, padding)

    if len(img.shape) == 3:
        img = crop_3dimage(img, beg_coords, end_coords)
    elif len(img.shape) == 2:
        img = crop_2dimage(img, beg_coords, end_coords)
    else:
        raise ValueError('Can only crop 2D or 3D images!')

    return img
1252789
def crop_resize(img, size):
   """"""
   if img.shape[0] < img.shape[1]:
       img = img.T
   # we crop image from center
   short_egde = min(img.shape[:2])
   yy = int((img.shape[0] - short_egde) / 2)
   xx = int((img.shape[1] - short_egde) / 2)
   crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
   # resize to 64, 64
   resized_img = transform.resize(crop_img, (size, size))
   resized_img *= 255
   return resized_img.astype("uint8")
769513
public function createCroppedImageVariant(ImageSize $sourceImageSize, $targetWidth, $targetHeight, $cropped = false, $quality = 95, $force = false)
	{
		// validate params
		if ( ! $sourceImageSize instanceof ImageSize) {
			throw new Exception\RuntimeException('ImageSize entity expected');
		}
		if (($targetWidth <= 0) || ($targetHeight <= 0)) {
			throw new Exception\RuntimeException('Dimensions are invalid');
		}
		
		if ( ! $sourceImageSize->isCropped()) {
			//throw new Exception\RuntimeException('Cannot resize non-cropped images with this metod');
		}
		
		$image = $sourceImageSize->getMaster();

		$sizeName = $this->getImageSizeNameForResizedCrop($targetWidth, $targetHeight, $sourceImageSize->getTargetWidth(), $sourceImageSize->getTargetHeight(), $sourceImageSize->getCropLeft(), $sourceImageSize->getCropTop(), $sourceImageSize->getCropWidth(), $sourceImageSize->getCropHeight(), $cropped);
			
		if ( ! $this->fileExists($image)) {
			$this->log()->warn("Image '{$image->getFileName()}' is missing in the filesystem, tried to resize cropped variant to {$sizeName}");

			return $sizeName;
		}
		
		$size = $image->getImageSize($sizeName);

		if (($size->getTargetHeight() == $targetHeight)
				&& ($size->getTargetWidth() == $targetWidth)
				&& ($size->getQuality() == $quality)
				&& ($size->getCropMode() == $cropped)
				&& empty($force)
		) {
			// nothing to update
			return $sizeName;
		}
		
		$size->setCropTop($sourceImageSize->getCropTop());
		$size->setCropLeft($sourceImageSize->getCropLeft());
		$size->setCropWidth($sourceImageSize->getCropWidth());
		$size->setCropHeight($sourceImageSize->getCropHeight());
		
		$size->setCropSourceWidth($sourceImageSize->getWidth());
		$size->setCropSourceHeight($sourceImageSize->getHeight());
	
		$size->setQuality($quality);
		$size->setCropMode($cropped);
		$size->setTargetWidth($targetWidth);
		$size->setTargetHeight($targetHeight);

		$variantFileName = $this->getImagePath($image, $sourceImageSize->getName());

		if ( ! file_exists($variantFileName)) {
			$this->log()->warn("Image cropped variant file {$variantFileName} is missing in the filesystem");

			return $sizeName;
		}
		
		$resizer = $this->getImageResizer();
		
		$resizer->setSourceFile($variantFileName)
				->setOutputQuality($quality)
				->setTargetWidth($targetWidth)
				->setTargetHeight($targetHeight)
				->setCropMode($cropped);

		$expectedSize = $resizer->getExpectedSize();
		$size->setWidth($expectedSize['width']);
		$size->setHeight($expectedSize['height']);

		$resizedFileDir = $this->getFilesystemDir($image)
				. self::RESERVED_DIR_SIZE . DIRECTORY_SEPARATOR
				. $size->getFolderName();

		if ( ! file_exists($resizedFileDir)) {
			$mkdirResult = mkdir($resizedFileDir, $this->folderAccessMode, true);
			if (empty($mkdirResult)) {
				throw new Exception\RuntimeException(
						'Could not create directory for resized image');
			}
		}

		$resizedFilePath = $resizedFileDir . DIRECTORY_SEPARATOR . $image->getFileName();
		$resizer->setOutputFile($resizedFilePath);
		$resizer->process();

		$entityManager = $this->getDoctrineEntityManager();

		$entityManager->persist($size);
		
		$size->setCropSourceWidth($sourceImageSize->getWidth());
		$size->setCropSourceHeight($sourceImageSize->getHeight());
		
		$entityManager->flush();

		return $sizeName;
	}
1088298
def create(self, original, size, crop, options=None):
        
        if options is None:
            options = self.evaluate_options()
        image = self.engine_load_image(original)
        image = self.scale(image, size, crop, options)
        crop = self.parse_crop(crop, self.get_image_size(image), size)
        image = self.crop(image, size, crop, options)
        image = self.colormode(image, options)
        return image
509935
def _random_crop(image, size):
  """"""
  bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
  random_image, bbox = distorted_bounding_box_crop(
      image,
      bbox,
      min_object_covered=0.1,
      aspect_ratio_range=(3. / 4, 4. / 3.),
      area_range=(0.08, 1.0),
      max_attempts=1,
      scope=None)
  bad = _at_least_x_are_true(tf.shape(image), tf.shape(random_image), 3)

  image = tf.cond(
      bad, lambda: _center_crop(_do_scale(image, size), size),
      lambda: tf.image.resize_bicubic([random_image], [size, size])[0])
  return image
2453
private void fitImageToView() {
        Drawable drawable = getDrawable();
        if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
            return;
        }
        if (matrix == null || prevMatrix == null) {
            return;
        }

        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();

        //
        // Scale image for view
        //
        float scaleX = (float) viewWidth / drawableWidth;
        float scaleY = (float) viewHeight / drawableHeight;

        switch (mScaleType) {
            case CENTER:
                scaleX = scaleY = 1;
                break;

            case CENTER_CROP:
                scaleX = scaleY = Math.max(scaleX, scaleY);
                break;

            case CENTER_INSIDE:
                scaleX = scaleY = Math.min(1, Math.min(scaleX, scaleY));

            case FIT_CENTER:
                scaleX = scaleY = Math.min(scaleX, scaleY);
                break;

            case FIT_XY:
                break;

            default:
                //
                // FIT_START and FIT_END not supported
                //
                throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END");

        }

        //
        // Center the image
        //
        float redundantXSpace = viewWidth - (scaleX * drawableWidth);
        float redundantYSpace = viewHeight - (scaleY * drawableHeight);
        matchViewWidth = viewWidth - redundantXSpace;
        matchViewHeight = viewHeight - redundantYSpace;
        if (!isZoomed() && !imageRenderedAtLeastOnce) {
            //
            // Stretch and center image to fit view
            //
            matrix.setScale(scaleX, scaleY);
            matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
            normalizedScale = 1;

        } else {
            //
            // These values should never be 0 or we will set viewWidth and viewHeight
            // to NaN in translateMatrixAfterRotate. To avoid this, call savePreviousImageValues
            // to set them equal to the current values.
            //
            if (prevMatchViewWidth == 0 || prevMatchViewHeight == 0) {
                savePreviousImageValues();
            }

            prevMatrix.getValues(m);

            //
            // Rescale Matrix after rotation
            //
            m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale;
            m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale;

            //
            // TransX and TransY from previous matrix
            //
            float transX = m[Matrix.MTRANS_X];
            float transY = m[Matrix.MTRANS_Y];

            //
            // Width
            //
            float prevActualWidth = prevMatchViewWidth * normalizedScale;
            float actualWidth = getImageWidth();
            translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth);

            //
            // Height
            //
            float prevActualHeight = prevMatchViewHeight * normalizedScale;
            float actualHeight = getImageHeight();
            translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight);

            //
            // Set the matrix to the adjusted scale and translate values.
            //
            matrix.setValues(m);
        }
        fixTrans();
        setImageMatrix(matrix);
    }
386184
def process(image, size, *args, **kwargs):
        
        from autodetect import smart_crop
        box_width, box_height = AutoCrop.parse_size(image, size)
        scaled_size, rect = smart_crop(box_width, box_height, image.filename)
        return image.resize(scaled_size, Image.ANTIALIAS).crop(tuple(rect))
973318
public int getResultingWidth() {

        int width = getResultingTargetWidth();
        if (width == -1) {
            if (isCropped()) {
                width = m_cropWidth;
            } else {
                width = m_orgWidth;
            }
        }
        return width;
    }
476454
def crop(self, image, size, crop, options):
        
        if not crop:
            return image
        return self.engine_crop(image, size, crop, options)
792430
def crop_resize_image(image: np.ndarray, size) -> np.ndarray:
    
    width, height = image.size
    if width > height:
        left = (width - height) / 2
        right = width - left
        top = 0
        bottom = height
    else:
        top = (height - width) / 2
        bottom = height - top
        left = 0
        right = width
    image = image.crop((left, top, right, bottom))
    image = image.resize(size, Image.ANTIALIAS)
    return image
1123267
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
    """"""
    h, w, _ = src.shape
    area = w*h
    for _ in range(10):
        new_area = random.uniform(min_area, 1.0) * area
        new_ratio = random.uniform(*ratio)
        new_w = int(new_area*new_ratio)
        new_h = int(new_area/new_ratio)

        if random.uniform(0., 1.) < 0.5:
            new_w, new_h = new_h, new_w

        if new_w > w or new_h > h:
            continue

        x0 = random.randint(0, w - new_w)
        y0 = random.randint(0, h - new_h)

        out = fixed_crop(src, x0, y0, new_w, new_h, size)
        return out, (x0, y0, new_w, new_h)

    return random_crop(src, size)
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)