Oto Shavadze
Oto Shavadze

Reputation: 42793

Crop image on left and right sides

I have an image with dimensions 1440 X 500.

I need to crop this image on the left at 200px and right at 200px. That is the new image must have dimensions of 1040 X 500.

I am trying this

$original_w = 1440;
$original_h = 500;

$new_w = 1040;
$new_h = 500;

$new_img = imagecreatetruecolor( $new_w, $new_h);
imagecopyresampled($new_img, $original_img, 200, 0, 200, 0, $new_w, $new_h, $original_w, $original_h);

I have not obtained a desirable result, please help, what I am doing wrong?

Upvotes: 1

Views: 1188

Answers (2)

zessx
zessx

Reputation: 68810

Reading PHP doc, you're using imagecopyresampled wrong :

imagecopyresampled ( 
   resource $dst_image , 
   resource $src_image , 
   int $dst_x , 
   int $dst_y , 
   int $src_x , 
   int $src_y , 
   int $dst_w , 
   int $dst_h , 
   int $src_w , 
   int $src_h 
)

So :

$original_w = 1440;
$original_h = 500;

$new_w = 1040;
$new_h = 500;

$new_img = imagecreatetruecolor( $new_w, $new_h);
imagecopyresampled($new_img, $original_img, 0, 0, 200, 0, $new_w, $new_h, $new_w, $new_h);

Copying the 1040*500 box from (200,0) coords to the new image, at (0,0) coords.

Upvotes: 3

Colin M
Colin M

Reputation: 13348

What you want is probably this:

imagecopyresampled($new_img, $original_img, -200, 0, 0, 0, $new_w, $new_h, $original_w, $original_h);

Which tells PHP to:

Copy the 1440x500 image starting at coordinate (0, 0) to a 1040x500 canvas starting at (-200, 0)

That way, you shift the original image 200 pixels left off of the canvas, and shrink the canvas width by 400px (so that the right 200px are also cut off).

I believe that should ge tyou what you're looking for.

Upvotes: 2

Related Questions