Resize and or crop the image.

@return void
516554
public function imageCopyResampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
    {
        if($this->copyStrategy == self::RESIZE) {
            $this->log("Copy by resize");
            imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
        } else {
            $this->log("Copy by resample");
            imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
        }
    }
1321849
protected function buildImageResize() {
    $image = Image::make($this->upload_path . $this->file_name)->orientate();

    $image->resize($this->preset->width, $this->preset->height , function ($constraint) {
      $constraint->aspectRatio();
      $constraint->upsize();
    });

    //if background_color is not set, do not resizeCanvas with black color, to avoid black zones in images. 
    if(isset($this->preset->background_color))
    {
      $image->resizeCanvas($this->preset->width, $this->preset->height, 'center', FALSE, $this->preset->background_color);
    }
    
    return $image;
  }
830837
private function resizeImage($request, $photoKey, $thumbnail)
    {
        $newRequest = $this->getSizeParameters($request);

        if ( $newRequest['width'][$photoKey] == 0 ) {
            $thumbnail = $request->has('crop_type') ? $this->getCropTypeSize($thumbnail,$request->get('crop_type')) : $thumbnail;
            $this->image->fit($thumbnail['width'], $thumbnail['height'], function($constraint)
            {
                $constraint->aspectRatio();
//                $constraint->upsize();
            });
            return;
        }
        $this->image->crop($newRequest['width'][$photoKey], $newRequest['height'][$photoKey], $newRequest['x'][$photoKey], $newRequest['y'][$photoKey])
            ->resize($thumbnail['width'], $thumbnail['height'], function($constraint)
            {
                $constraint->aspectRatio();
            });
    }
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;
    }
327559
public function runCropResize(Image $image, $width, $height)
    {
        list($resize_width, $resize_height) = $this->resolveCropResizeDimensions($image, $width, $height);

        $zoom = $this->getCrop()[2];

        $image->resize($resize_width * $zoom, $resize_height * $zoom, function ($constraint) {
            $constraint->aspectRatio();
        });

        list($offset_x, $offset_y) = $this->resolveCropOffset($image, $width, $height);

        return $image->crop($width, $height, $offset_x, $offset_y);
    }
522218
def _resize(image, width, height, crop):
    
    ext = os.path.splitext(image.name)[1].strip(".")

    with Image(file=image, format=ext) as b_image:
        # Account for orientation
        if ORIENTATION_TYPES.index(b_image.orientation) > 4:
            # Flip
            target_aspect = float(width) / float(height)
            aspect = float(b_image.height) / float(b_image.width)
        else:
            target_aspect = float(width) / float(height)
            aspect = float(b_image.width) / float(b_image.height)

        # Fix rotation
        b_image.auto_orient()

        # Calculate target size
        target_aspect = float(width) / float(height)
        aspect = float(b_image.width) / float(b_image.height)

        if ((target_aspect > aspect and not crop) or
                (target_aspect <= aspect and crop)):
            # target is wider than image, set height as maximum
            target_height = height

            # calculate width
            # -  iw / ih = tw / th (keep aspect)
            # => th ( iw / ih ) = tw
            target_width = float(target_height) * aspect

            if crop:
                # calculate crop coords
                # -  ( tw - w ) / 2
                target_left = (float(target_width) - float(width)) / 2
                target_left = int(round(target_left))
                target_top = 0

            # correct floating point error, and convert to int, round in the
            # direction of the requested width
            if width >= target_width:
                target_width = int(math.ceil(target_width))
            else:
                target_width = int(math.floor(target_width))
        else:
            # image is wider than target, set width as maximum
            target_width = width

            # calculate height
            # -  iw / ih = tw / th (keep aspect)
            # => tw / ( iw / ih ) = th
            target_height = float(target_width) / aspect

            if crop:
                # calculate crop coords
                # -  ( th - h ) / 2
                target_top = (float(target_height) - float(height)) / 2
                target_top = int(round(target_top))
                target_left = 0

            # correct floating point error and convert to int
            if height >= target_height:
                target_height = int(math.ceil(target_height))
            else:
                target_height = int(math.floor(target_height))

        # strip color profiles
        b_image.strip()

        # Resize
        b_image.resize(target_width, target_height)

        if crop:
            # Crop to target
            b_image.crop(left=target_left, top=target_top, width=width,
                         height=height)

        # Save to temporary file
        temp_file = tempfile.TemporaryFile()
        b_image.save(file=temp_file)
        # Rewind the file
        temp_file.seek(0)
        return temp_file
1216550
public function reprocess()
    {
        if (empty($this->getAttribute('filename'))) {
            return;
        }

        foreach ($this->styles as $name => $style) {
            if (empty($file = $this->path($name))) {
                continue;
            }

            $file = $this->getFileManager()->make($file);

            if ($style && $file->isImage()) {
                $file = $this->getResizer()
                    ->resize($file, $style);
            }
            else {
                $file = $file->getRealPath();
            }

            $filePath = $this->path($name);
            $this->move($file, $filePath);
        }
    }
1112588
public function performCrop()
    {
        $req_post = esc_html( $_POST['post'] );
        if (!current_user_can('edit_post', $req_post))
            json_response([
                'status'=>'error',
                'message'=>'You are not strong enough, smart enough or fast enough.'
                          ]);


        $size = esc_html($_POST['size']);
        $crop_width = esc_html($_POST['width']);
        $crop_height = esc_html($_POST['height']);
        $crop_x = esc_html($_POST['x']);
        $crop_y = esc_html($_POST['y']);

        $img_path = _load_image_to_edit_path( $req_post );
        $meta = wp_get_attachment_metadata( $req_post );
        $img_editor = wp_get_image_editor( $img_path );
        if (is_wp_error($img_editor))
            json_response([
                              'status'=>'error',
                              'message'=>'Could not create image editor.'
                          ]);

        $crop_size=ilab_get_image_sizes($size);
        $dest_width = $crop_size['width'];
        $dest_height = $crop_size['height'];

        $img_editor->crop($crop_x, $crop_y, $crop_width, $crop_height, $dest_width, $dest_height, false );
        $img_editor->set_quality($this->cropQuality);
        $save_path_parts = pathinfo($img_path);

        $path_url=parse_url($img_path);
        if (($path_url!==false) && (isset($path_url['scheme'])))
        {
            $parsed_path=pathinfo($path_url['path']);
            $img_subpath=apply_filters('ilab_s3_process_file_name',$parsed_path['dirname']);

            $upload_dir=wp_upload_dir();
            $save_path=$upload_dir['basedir'].$img_subpath;
            @mkdir($save_path,0777,true);
        }
        else
            $save_path=$save_path_parts['dirname'];

        $extension=$save_path_parts['extension'];
        $filename=preg_replace('#^(IL[0-9-]*)#','',$save_path_parts['filename']);
        $filename='IL'.date("YmdHis").'-'.$filename.'-'.$dest_width.'x'.$dest_height.'.'.$extension;

        if (isset($meta['sizes'][$size]))
        {
            $meta['sizes'][$size]['file']=$filename;
            $meta['sizes'][$size]['width']=$dest_width;
            $meta['sizes'][$size]['height']=$dest_height;
            $meta['sizes'][$size]['crop']=[
                'x'=>round($crop_x),
                'y'=>round($crop_y),
                'w'=>round($crop_width),
                'h'=>round($crop_height)
            ];
        }
        else
        {
            $meta['sizes'][$size] = array(
                'file' => $filename,
                'width' => $dest_width,
                'height' => $dest_height,
                'mime-type' => $meta['sizes']['thumbnail']['mime-type'],
                'crop'=> [
                    'x'=>round($crop_x),
                    'y'=>round($crop_y),
                    'w'=>round($crop_width),
                    'h'=>round($crop_height)
                ]
            );
        }

        $img_editor->save($save_path . '/' . $filename);

        // Let S3 upload the new crop
        $processedSize = apply_filters('ilab_s3_process_crop', $size, $save_path, $filename, $meta['sizes'][$size]);
        if ($processedSize)
            $meta['sizes'][$size] = $processedSize;

        wp_update_attachment_metadata($req_post, $meta);

        $attrs = wp_get_attachment_image_src($req_post, $size);
        list($full_src,$full_width,$full_height,$full_cropped)=$attrs;

        json_response([
            'status'=>'ok',
            'src'=>$full_src,
            'width'=>$full_width,
            'height'=>$full_height
        ]);
    }
1167238
public function resizeAndCrop($targetWidth, $targetHeight)
    {
        if ($this->getAutoOrient()) {
            $this->autoOrient();
        }

        // First get the size that we can use to safely trim down the image without cropping any sides
        $crop = $this->getSafeResizeOffset($this->originalImage, $targetWidth, $targetHeight);
        // Resize the image
        $this->originalImage->resizeImage($crop['width'], $crop['height'], $this->getFilter(), $this->getBlur());
        // Get the offset for cropping the image further
        $offset = $this->getSpecialOffset($this->originalImage, $targetWidth, $targetHeight);
        // Crop the image
        $this->originalImage->cropImage($targetWidth, $targetHeight, $offset['x'], $offset['y']);

        return $this->originalImage;
    }
245211
public function cropImages($request)
    {
        $path = $request['path'];
        $coords = $this->getCropCoordinates($request);
        $images = $this->getNewImages();

        $full = reset($this->_imageTypes);

        $cropperImage = $this->getTempImage();
        $cropperImage->setResourceFromFile(UPLOADS_PATH . 'tmp/' . $path);

        $originalImage = $this->getTempImage();
        $originalImage->setResourceFromFile(UPLOADS_PATH . 'tmp/' . str_replace('crop-', '', $path));

        $images[$full]->setResourceFromFile($originalImage->getFile());
        $images[$full]->save();

        $crop = next($this->_imageTypes);
        $images[$crop]->copyResource($images[$full]);

        $ratio = $images[$full]->getWidth() / $cropperImage->getWidth();
        $adjustX = round($coords['x'] * $ratio);
        $adjustY = round($coords['y'] * $ratio);
        $adjustWidth = round($coords['width'] * $ratio);
        $adjustHeight = round($coords['height'] * $ratio);

        $images[$crop]->crop(
            $adjustX, $adjustY,
            $this->getImageWidth($crop), $this->getImageHeight($crop),
            $adjustWidth, $adjustHeight);

        while ($size = next($this->_imageTypes)) {
            $images[$size]->copyResource($images[$crop])->resize()->unsharpMask()->save();
        }

        $images[$crop]->unsharpMask()->save();

        Nip_File_System::instance()->deleteFile($cropperImage->getFile());
        Nip_File_System::instance()->deleteFile($originalImage->getFile());

        return $images['default'];
    }
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")
936540
public function resize(int $width = 0, int $height = 0)
    {
        if (!$width && !$height) {
            throw new ImageException('You must supply at least one dimension');
        }
        $iw = $this->info[0];
        $ih = $this->info[1];
        if (!$height || !$width) {
            if (!$width) {
                $width  = $height / $ih * $iw;
            }
            if (!$height) {
                $height = $width  / $iw * $ih;
            }
        }
        $di = imagecreatetruecolor($width, $height);
        imagecopyresized($di, $this->data, 0, 0, 0, 0, $width, $height, $iw, $ih);
        $this->data = $di;
    }
438898
private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight, $cropPos)
		# Author:     Jarrod Oberto
		# Date:       15-09-08
		# Purpose:    Crops the image
		# Param in:   $newWidth:
		#             $newHeight:
		# Param out:  n/a
		# Reference:
		# Notes:
		#
	{

		// *** Get cropping co-ordinates
		$cropArray = $this->getCropPlacing($optimalWidth, $optimalHeight, $newWidth, $newHeight, $cropPos);
		$cropStartX = $cropArray['x'];
		$cropStartY = $cropArray['y'];

		// *** Crop this bad boy
		$crop = imagecreatetruecolor($newWidth, $newHeight);
		$this->keepTransparancy($optimalWidth, $optimalHeight, $crop);
		imagecopyresampled($crop, $this->imageResized, 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight, $newWidth, $newHeight);

		$this->imageResized = $crop;

		// *** Set new width and height to our variables
		$this->width = $newWidth;
		$this->height = $newHeight;

	}
87183
def resize(image, width=None, height=None, crop=False, namespace="resized"):
    
    return resize_lazy(image=image, width=width, height=height, crop=crop,
                       namespace=namespace, as_url=True)
1059019
public function resize($crop = false)
    {
        if ($crop) {
            return $this->resizeCrop();
        } else {
            $sourceDimension = $this->sourceImageFile->getDimension();
            $resampleDimension = $this->resampleImageFile->getDimension();

            if (($sourceDimension->getWidth() <= $resampleDimension->getWidth()) && ($sourceDimension->getHeight() <= $resampleDimension->getHeight())) {
                return true;
            } //no resizing needed

            //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;
            }

            if (function_exists('imagecreatetruecolor')) {
                $this->resampleImageResource = imagecreatetruecolor($resizeWidth, $resizeHeight);

                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,
                    0,
                    0,
                    0,
                    0,
                    $resizeWidth,
                    $resizeHeight,
                    $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 imagecopyresampled(
                    $this->resampleImageResource,
                    $this->sourceImageResource,
                    0,
                    0,
                    0,
                    0,
                    $resizeWidth,
                    $resizeHeight,
                    $sourceDimension->getWidth(),
                    $sourceDimension->getHeight()
                );
            }
        }
    }
106270
public function resize_image($w, $h, $crop = false)
    {
        list($width, $height) = getimagesize($this->file);
        $r = $width / $height;
        if ($crop) {
            if ($width > $height) {
                $width = ceil($width - ($width * abs($r - $w / $h)));
            } else {
                $height = ceil($height - ($height * abs($r - $w / $h)));
            }
            $newwidth = $w;
            $newheight = $h;
        } else {
            if ($w / $h > $r) {
                $newwidth = $h * $r;
                $newheight = $h;
            } else {
                $newheight = $w / $r;
                $newwidth = $w;
            }
        }
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $this->image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        $this->image = $dst;
    }
1352494
public function onResizeImage()
    {
        $this->abortIfReadOnly();

        $cropSessionKey = Input::get('cropSessionKey');
        if (!preg_match('/^[0-9a-z]+$/', $cropSessionKey)) {
            throw new ApplicationException('Invalid input data');
        }

        $width = trim(Input::get('width'));
        if (!strlen($width) || !ctype_digit($width)) {
            throw new ApplicationException('Invalid input data');
        }

        $height = trim(Input::get('height'));
        if (!strlen($height) || !ctype_digit($height)) {
            throw new ApplicationException('Invalid input data');
        }

        $path = Input::get('path');
        $path = MediaLibrary::validatePath($path);

        $params = array(
            'width' => $width,
            'height' => $height
        );

        return $this->getCropEditImageUrlAndSize($path, $cropSessionKey, $params);
    }