DingDong
DingDong

Reputation: 75

PHP split jpg image into two equal images and save

I have a jpg picture which I want to split into two equal images. The split should happen in the horizontal center of the image and save both parts (left part, right part). For instance an image of 500x300 would be split into two images each 250x300. I am not familiar with the right image processing function, and when checking PHP's docs it clearly warns that 'imagecrop()' is not documented (http://php.net/manual/en/function.imagecrop.php). Also on stackoverflow, the only thing which I found is this snippet which I tried to play around with:

// copy left third to output image
imagecopy($output, $orig,$padding,$padding,0, 0,$width/3,$height);
// copy central third to output image
imagecopy($output, $orig,2*$padding+$width/3,$padding,$width/3, 0,$width/3,$height);

Maybe you could point me to the right direction.

Thanks a lot

Upvotes: 3

Views: 2406

Answers (1)

Gvidas
Gvidas

Reputation: 1964

Function imagecopy() is well documented & can do exactly what you want. For example:

imagecopy($leftSide, $orig, 0, 0, 0, 0, $width/2, $height);
imagecopy($rightSide, $orig, 0, 0, $width/2, 0, $width/2, $height);

Ofcourse first you need to write your image in variable $orig with functions like: imagecreatefrompng, imagecreatefromgif, etc. EG:

$orig= imagecreatefromjpeg('php.jpg');

Then you need to create new empty image variables for both image sides: with imagecreatetruecolor, eg:

$leftSide = imagecreatetruecolor($width/2, $height);
$rightSide = imagecreatetruecolor($width/2, $height);

And then just save those two variables to new files using functions by needed extension, like imagejpeg. EG:

imagejpeg($leftSide, 'leftSide.jpg');
imagejpeg($rightSide, 'rightSide.jpg');

Upvotes: 7

Related Questions