php 实现切图
使用 PHP 实现图片切割
GD 库基础切割方法
安装 GD 库后可以通过 imagecrop() 函数实现基础切割
$srcImage = imagecreatefromjpeg('input.jpg');
$croppedImage = imagecrop($srcImage, ['x' => 100, 'y' => 50, 'width' => 300, 'height' => 200]);
imagejpeg($croppedImage, 'output.jpg');
imagedestroy($srcImage);
imagedestroy($croppedImage);
等比例分割多张图片
将大图分割为指定数量的小图
function splitImage($srcPath, $rows, $cols, $outputPrefix) {
$image = imagecreatefromjpeg($srcPath);
$width = imagesx($image);
$height = imagesy($image);
$tileWidth = $width / $cols;
$tileHeight = $height / $rows;
for ($row = 0; $row < $rows; $row++) {
for ($col = 0; $col < $cols; $col++) {
$tile = imagecrop($image, [
'x' => $col * $tileWidth,
'y' => $row * $tileHeight,
'width' => $tileWidth,
'height' => $tileHeight
]);
imagejpeg($tile, "{$outputPrefix}_{$row}_{$col}.jpg");
imagedestroy($tile);
}
}
imagedestroy($image);
}
保持宽高比的智能裁剪
根据目标尺寸自动计算最佳裁剪区域
function smartCrop($srcPath, $targetWidth, $targetHeight) {
$src = imagecreatefromjpeg($srcPath);
$srcWidth = imagesx($src);
$srcHeight = imagesy($src);
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if ($srcRatio > $targetRatio) {
$cropWidth = $srcHeight * $targetRatio;
$cropHeight = $srcHeight;
$x = ($srcWidth - $cropWidth) / 2;
$y = 0;
} else {
$cropWidth = $srcWidth;
$cropHeight = $srcWidth / $targetRatio;
$x = 0;
$y = ($srcHeight - $cropHeight) / 2;
}
$cropped = imagecrop($src, [
'x' => $x,
'y' => $y,
'width' => $cropWidth,
'height' => $cropHeight
]);
$resized = imagescale($cropped, $targetWidth, $targetHeight);
imagejpeg($resized, 'smart_crop_output.jpg');
imagedestroy($src);
imagedestroy($cropped);
imagedestroy($resized);
}
使用 Imagick 扩展处理
Imagick 提供更强大的图像处理能力
$imagick = new Imagick('input.jpg');
$imagick->cropImage(200, 150, 50, 30); // 宽度,高度,X起点,Y起点
$imagick->writeImage('output_crop.jpg');
$imagick->clear();
批量处理目录图片
遍历目录处理所有图片文件

$directory = 'images/';
$files = scandir($directory);
foreach ($files as $file) {
if (in_array(pathinfo($file, PATHINFO_EXTENSION), ['jpg', 'png'])) {
$srcPath = $directory . $file;
$outputPath = $directory . 'cropped_' . $file;
$image = imagecreatefromjpeg($srcPath);
$cropped = imagecrop($image, ['x' => 0, 'y' => 0, 'width' => 500, 'height' => 500]);
if ($cropped !== false) {
imagejpeg($cropped, $outputPath);
imagedestroy($cropped);
}
imagedestroy($image);
}
}






