Common argument checking for crop and resize
14488
function checkCommonArgs(args) {
        if (args.length < 2) throw new Error("File1, File2, and callback required");
        if (typeof args.at(1) != "string") throw new Error("File2 required");
        if (typeof args.at(0) != "string") throw new Error("File1 required");
        if (!args.callbackGiven()) throw new Error("Callback required");
    }
867711
def zoom_crop(scale:float, do_rand:bool=False, p:float=1.0):
    ""
    zoom_fn = rand_zoom if do_rand else zoom
    crop_fn = rand_crop if do_rand else crop_pad
    return [zoom_fn(scale=scale, p=p), crop_fn()]
865183
public function crop() {

		$args = func_get_args();
		
		$srcAspectRatio = $this->srcWidth / $this->srcHeight;
		
		// single float value given, represents aspect ratio of cropped image

		if(count($args) === 1) {

			if(!is_numeric($args[0]) || $args[0] <= 0) {
				throw new ImageModifierException('Invalid dimension(s) for cropping: ' . $args[0] . '.');
			}
		
			if($srcAspectRatio <= $args[0]) {
		
				// width determines

				$left = $right = 0;

				if($srcAspectRatio >= 1) {

				    // assume landscape

                    $top = $bottom = round(($this->srcHeight - $this->srcWidth / $args[0]) / 2);

                }

				else {

				    // assume portrait and shift crop somewhat up

                    $top = round(($this->srcHeight - $this->srcWidth / $args[0]) / 3);
                    $bottom	= round(($this->srcHeight - $this->srcWidth / $args[0]) * 2 / 3);

                }
			}

			else {
		
				// height determines

				$top = $bottom = 0;
				$left = $right = round(($this->srcWidth - $this->srcHeight * $args[0]) / 2);
			}
		}
		
		// width and height given
		
		else if(count($args) === 2) {

			$width	= (int) $args[0];
			$height	= (int) $args[1];
		
			if($width > 0 && $height > 0) {
				$left = $right = round(($this->srcWidth - $width) / 2);
		
				if($srcAspectRatio >= 1) {

					// landscape

					$top = $bottom = round(($this->srcHeight - $height) / 2);
				}

				else {

					// portrait and shift crop up

					$top	= round(($this->srcHeight - $height) / 3);
					$bottom	= round(($this->srcHeight - $height) * 2 / 3);
				}
			}
		
			else {
				throw new ImageModifierException('Invalid dimension(s) for cropping: ' . $width . ', ' . $height . '.');
			}
		}
		
		// top, left, bottom, right
		
		else if(count($args) == 4) {

			$top	= (int) $args[0];
			$left	= (int) $args[1];
			$bottom	= (int) $args[2];
			$right	= (int) $args[3];

		}

		else {
			throw new ImageModifierException('Insufficient arguments for cropping.');
		}
		
		// skip queuing when there is nothing to crop
		
		if(!$top && !$bottom && !$left && !$right) {

			return;

		}

		$todo = new \stdClass();
		
		$todo->method		= __FUNCTION__;
		$todo->parameters	= array($top, $right, $bottom, $left);

		$this->queue[] = $todo;
		
		$this->srcWidth		= $this->srcWidth - $left - $right;
		$this->srcHeight	= $this->srcHeight - $top - $bottom;

	}
1370896
def cropping_mask
      return if crop_from.blank? || crop_size.blank?
      crop_from = point_from_string(read_attribute(:crop_from))
      crop_size = sizes_from_string(read_attribute(:crop_size))

      point_and_mask_to_points(crop_from, crop_size)
    end
81666
function(size) {
    return function limitResolution(params) {
      var height = params.height;
      if (height) {
        var requiredPixels = pixelRatio() * height;
        var minFov = 2 * Math.atan(requiredPixels / size);
        params.fov = clamp(params.fov, minFov, Infinity);
      }
      return params;
    };
  }
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))
434149
function crop($x1,$y1,$x2,$y2) {
		$tmp=imagecreatetruecolor($width=$x2-$x1+1,$height=$y2-$y1+1);
		imagesavealpha($tmp,TRUE);
		imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
		imagecopyresampled($tmp,$this->data,
			0,0,$x1,$y1,$width,$height,$width,$height);
		imagedestroy($this->data);
		$this->data=$tmp;
		return $this->save();
	}
645662
def crop_or_pad(im, size, value=0):
    
    diff = [im.shape[index] - size[index] for index in (0, 1)]
    im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 + size[1]]
    return im2
533700
def on_resize(self, *args):
        """"""
        # pylint: disable=W0613
        #         Unused argument 'args'
        self.screen.style.name_len = min(self.screen.style.name_len,
                                         self.term.width - 15)
        assert self.term.width >= self.screen.hint_width, (
            'Screen to small {}, must be at least {}'.format(
                self.term.width, self.screen.hint_width))
        self._set_lastpage()
        self.dirty = self.STATE_REFRESH
69290
def image_postprocess(imagefile, output, size, crop, render):
    
    try:
        from PIL import Image
    except ImportError:
        import Image

    img = Image.open(imagefile)
    size_crop = None
    img_resized = img
    if size and crop and crop.lower() == 'true':
        width_raw, height_raw = img.size
        width, height = size
        height_better = int(height_raw * (float(width) / width_raw))
        if height < height_better:
            size_crop = (0, 0, width, height)

    try:
        if size_crop:
            size_better = width, height_better
            img_better = img.resize(size_better, Image.ANTIALIAS)
            img_resized = img_better.crop(size_crop)
        elif size:
            img_resized = img.resize(size, Image.ANTIALIAS)

        # If save with 'bmp' use default mode('RGBA'), it will raise:
        # "IOError: cannot write mode RGBA as BMP".
        # So, we need convert image mode
        # from 'RGBA' to 'RGB' for 'bmp' format.
        if render == 'bmp':
            img_resized = img_resized.convert('RGB')
        # Fix IOError: cannot write mode RGBA as XBM
        elif render == 'xbm':
            img_resized = img_resized.convert('1')
        # Works with either filename or file-like object
        img_resized.save(output, render)
    except KeyError:
        raise UnsupportedImageFormat
    except IOError as e:
        raise CaptureError(e)
791220
private function crop($optimal_width, $optimal_height, $new_width, $new_height)
    {
        // Find center - this will be used for the crop
        $crop_start_x = ($optimal_width  / 2) - ($new_width  / 2);
        $crop_start_y = ($optimal_height / 2) - ($new_height / 2);

        $crop = $this->image_resized;

        $dest_offset_x = max(0, -$crop_start_x);
        $dest_offset_y = max(0, -$crop_start_y);
        $crop_start_x  = max(0, $crop_start_x);
        $crop_start_y  = max(0, $crop_start_y);
        $dest_width    = min($optimal_width, $new_width);
        $dest_height   = min($optimal_height, $new_height);

        // Now crop from center to exact requested size
        $this->image_resized = imagecreatetruecolor($new_width, $new_height);

        imagealphablending($crop, true);
        imagealphablending($this->image_resized, false);
        imagesavealpha($this->image_resized, true);

        imagefilledrectangle($this->image_resized, 0, 0, $new_width, $new_height,
            imagecolorallocatealpha($this->image_resized, 255, 255, 255, 127)
        );

        imagecopyresampled($this->image_resized, $crop, $dest_offset_x, $dest_offset_y, $crop_start_x, $crop_start_y, $dest_width, $dest_height, $dest_width, $dest_height);

        return true;
    }
477574
public function resizeCrop()
    {
        $sourceDimension = $this->sourceImageFile->getDimension();
        $resampleDimension = $this->resampleImageFile->getDimension();

        if ($resampleDimension->getOrientation() === 'SQUARE') {
            if ($sourceDimension->getOrientation() === 'LANDSCAPE') {
                $sourceSquareSize = $sourceDimension->getHeight();

                $sourceDimension = new Dimension(
                    $sourceSquareSize,
                    $sourceSquareSize,
                    ($sourceDimension->getWidth() - $sourceDimension->getHeight()) / 2,
                    0
                );
            } elseif ($sourceDimension->getOrientation() === 'PORTRAIT') {
                $sourceSquareSize = $sourceDimension->getWidth();

                $sourceDimension = new Dimension(
                    $sourceSquareSize,
                    $sourceSquareSize,
                    0,
                    ($sourceDimension->getHeight() - $sourceDimension->getWidth()) / 2
                );
            }
        } else {

            //try max width first...
            $resizeRatio = $resampleDimension->getWidth() / $sourceDimension->getWidth();
            $resizeWidth = $resampleDimension->getWidth();
            $resizeHeight = $sourceDimension->getHeight() * $resizeRatio;

            //if that didn't work
            if ($resizeHeight > $resampleDimension->getHeight()) {
                $resizeRatio = $resampleDimension->getHeight() / $sourceDimension->getHeight();
                $resizeHeight = $resampleDimension->getHeight();
                $resizeWidth = $sourceDimension->getWidth() * $resizeRatio;
            }

            switch ($resampleDimension->getFocus()) {
                default:
                case 'CENTER':

                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        ($sourceDimension->getWidth() / 2) - ($resizeWidth / 2),
                        ($sourceDimension->getHeight() / 2) - ($resizeHeight / 2)
                    );

                    break;
                case 'NORTH':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        ($sourceDimension->getWidth() - $resizeWidth) / 2,
                        0
                    );
                    break;
                case 'NORTHWEST':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        0,
                        0
                    );
                    break;
                case 'NORTHEAST':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        $sourceDimension->getWidth() - $resizeWidth,
                        0
                    );
                    break;
                case 'SOUTH':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        ($sourceDimension->getWidth() - $resizeWidth) / 2,
                        $sourceDimension->getHeight() - $resizeHeight
                    );
                    break;
                case 'SOUTHWEST':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        0,
                        $sourceDimension->getHeight() - $resizeHeight
                    );
                    break;
                case 'SOUTHEAST':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        $sourceDimension->getWidth() - $resizeWidth,
                        $sourceDimension->getHeight() - $resizeHeight
                    );
                    break;
                case 'WEST':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        0,
                        ($sourceDimension->getHeight() - $resizeHeight) / 2
                    );
                    break;
                case 'EAST':
                    $sourceDimension = new Dimension(
                        $resizeWidth,
                        $resizeHeight,
                        $sourceDimension->getWidth() - $resizeWidth,
                        ($sourceDimension->getHeight() - $resizeHeight) / 2
                    );
                    break;
            }
        }

        $resampleAxis = $this->resampleImageFile->getDimension()->getAxis();
        $sourceAxis = $sourceDimension->getAxis();

        if (function_exists('imagecreatetruecolor')) {
            $this->resampleImageResource = imagecreatetruecolor(
                $resampleDimension->getWidth(),
                $resampleDimension->getHeight()
            );

            imagealphablending($this->resampleImageResource, false);
            imagesavealpha($this->resampleImageResource, true);

            $transparent = imagecolorallocatealpha($this->resampleImageResource, 255, 255, 255, 127);
            imagefilledrectangle($this->resampleImageResource, 0, 0, $resampleDimension->getWidth(),
                $resampleDimension->getHeight(), $transparent);

            return imagecopyresampled(
                $this->resampleImageResource,
                $this->sourceImageResource,
                $resampleAxis->getX(),
                $resampleAxis->getY(),
                $sourceAxis->getX(),
                $sourceAxis->getY(),
                $resampleDimension->getWidth(),
                $resampleDimension->getHeight(),
                $sourceDimension->getWidth(),
                $sourceDimension->getHeight()
            );
        } else {
            $this->resampleImageResource = imagecreate($resampleDimension->getWidth(),
                $resampleDimension->getHeight());

            imagealphablending($this->resampleImageResource, false);
            imagesavealpha($this->resampleImageResource, true);

            $transparent = imagecolorallocatealpha($this->resampleImageResource, 255, 255, 255, 127);
            imagefilledrectangle($this->resampleImageResource, 0, 0, $resampleDimension->getWidth(),
                $resampleDimension->getHeight(), $transparent);

            return imagecopyresized(
                $this->resampleImageResource,
                $this->sourceImageResource,
                $resampleAxis->getX(),
                $resampleAxis->getY(),
                $sourceAxis->getX(),
                $sourceAxis->getY(),
                $resampleDimension->getWidth(),
                $resampleDimension->getHeight(),
                $sourceDimension->getWidth(),
                $sourceDimension->getHeight()
            );
        }
    }
771044
def crop_to_fit(self, image_size, view_size):
        
        self.blipFill.crop(self._fill_cropping(image_size, view_size))
267486
public void setCropped(boolean cropped) {

        if (cropped) {
            m_heightBox.setEnabled(false);
            m_widthBox.setEnabled(false);
            m_selectBox.setEnabled(false);
            m_resetSize.disable(Messages.get().key(Messages.GUI_PREVIEW_BUTTON_DIS_CROPPED_0));
            m_ratioLock.disable(Messages.get().key(Messages.GUI_PREVIEW_BUTTON_DIS_CROPPED_0));
            m_cropButton.disable(Messages.get().key(Messages.GUI_PREVIEW_BUTTON_DIS_CROPPED_0));
            if (m_formEnabled) {
                m_removeCropButton.enable();
            }
            m_removeCropButton.setVisible(true);
            return;
        }
        if (m_formEnabled) {
            m_cropButton.enable();
            m_heightBox.setEnabled(true);
            m_widthBox.setEnabled(true);
            m_selectBox.setEnabled(true);
            m_resetSize.enable();
            m_ratioLock.enable();
        }
        m_removeCropButton.setVisible(false);
    }
1106562
private function getCropPlacing($optimalWidth, $optimalHeight, $newWidth, $newHeight, $pos = 'm')
		#
		# Author:   Jarrod Oberto
		# Date:   July 11
		# Purpose:  Set the cropping area.
		# Params in:
		# Params out: (array) the crop x and y co-ordinates.
		# Notes:    When specifying the exact pixel crop position (eg 10x15), be
		#       very careful as it's easy to crop out of the image leaving
		#       black borders.
		#
	{
		$pos = fix_strtolower($pos);

		// *** If co-ords have been entered
		if (strstr($pos, 'x'))
		{
			$pos = str_replace(' ', '', $pos);

			$xyArray = explode('x', $pos);
			list($cropStartX, $cropStartY) = $xyArray;

		}
		else
		{

			switch ($pos)
			{
				case 'tl':
					$cropStartX = 0;
					$cropStartY = 0;
					break;

				case 't':
					$cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
					$cropStartY = 0;
					break;

				case 'tr':
					$cropStartX = $optimalWidth - $newWidth;
					$cropStartY = 0;
					break;

				case 'l':
					$cropStartX = 0;
					$cropStartY = ($optimalHeight / 2) - ($newHeight / 2);
					break;

				case 'm':
					$cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
					$cropStartY = ($optimalHeight / 2) - ($newHeight / 2);
					break;

				case 'r':
					$cropStartX = $optimalWidth - $newWidth;
					$cropStartY = ($optimalHeight / 2) - ($newHeight / 2);
					break;

				case 'bl':
					$cropStartX = 0;
					$cropStartY = $optimalHeight - $newHeight;
					break;

				case 'b':
					$cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
					$cropStartY = $optimalHeight - $newHeight;
					break;

				case 'br':
					$cropStartX = $optimalWidth - $newWidth;
					$cropStartY = $optimalHeight - $newHeight;
					break;

				case 'auto':
					// *** If image is a portrait crop from top, not center. v1.5
					if ($optimalHeight > $optimalWidth)
					{
						$cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
						$cropStartY = ($this->cropFromTopPercent / 100) * $optimalHeight;
					}
					else
					{

						// *** Else crop from the center
						$cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
						$cropStartY = ($optimalHeight / 2) - ($newHeight / 2);
					}
					break;

				default:
					// *** Default to center
					$cropStartX = ($optimalWidth / 2) - ($newWidth / 2);
					$cropStartY = ($optimalHeight / 2) - ($newHeight / 2);
					break;
			}
		}

		return array( 'x' => $cropStartX, 'y' => $cropStartY );
	}
1176089
def crop(self, *args, **kwargs):
        """"""
        return self._generate_scene_func(self._scenes, 'crop', True, *args, **kwargs)
595206
def crop(im, r, c, sz_h, sz_w):
    '''
    
    '''
    return im[r:r+sz_h, c:c+sz_w]