PHP 将 jpg 图像分割成两个相等的图像并保存

Din*_*ong 3 php image crop save

我有一张 jpg 图片,我想将其分成两个相等的图像。分割应该发生在图像的水平中心并保存两个部分(左部分,右部分)。例如,一张 500x300 的图像将被分成两个图像,每个图像都是 250x300。我不熟悉正确的图像处理功能,在检查 PHP 的文档时,它明确警告没有记录“imagecrop()”(http://php.net/manual/en/function.imagecrop.php)。同样在stackoverflow上,我发现的唯一一件事就是我试图玩弄的这个片段:

// 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);
Run Code Online (Sandbox Code Playgroud)

也许你可以指出我正确的方向。

非常感谢

小智 7

功能imagecopy()有据可查,可以完全满足您的要求。例如:

imagecopy($leftSide, $orig, 0, 0, 0, 0, $width/2, $height);
imagecopy($rightSide, $orig, 0, 0, $width/2, 0, $width/2, $height);
Run Code Online (Sandbox Code Playgroud)

当然,首先您需要$orig使用以下函数将图像写入变量:imagecreatefrompngimagecreatefromgif等。例如:

$orig= imagecreatefromjpeg('php.jpg');
Run Code Online (Sandbox Code Playgroud)

然后,您需要为图像两侧创建新的空图像变量:使用imagecreatetruecolor,例如:

$leftSide = imagecreatetruecolor($width/2, $height);
$rightSide = imagecreatetruecolor($width/2, $height);
Run Code Online (Sandbox Code Playgroud)

然后只需使用所需扩展名的函数将这两个变量保存到新文件中,例如imagejpeg。例如:

imagejpeg($leftSide, 'leftSide.jpg');
imagejpeg($rightSide, 'rightSide.jpg');
Run Code Online (Sandbox Code Playgroud)