要在PHP中创建缩略图和剪切图,可以使用GD库。以下是一个示例代码,可以将原始图像缩小为指定大小的缩略图,并将图像剪切为指定大小的剪切图。
// 原始图像路径
$originalImage = 'path/to/original/image.jpg';
// 缩略图路径
$thumbnailImage = 'path/to/thumbnail/image.jpg';
// 剪切图路径
$croppedImage = 'path/to/cropped/image.jpg';
// 缩略图大小
$thumbnailWidth = 200;
$thumbnailHeight = 200;
// 剪切图大小
$croppedWidth = 400;
$croppedHeight = 300;
// 创建原始图像的GD图像对象
$original = imagecreatefromjpeg($originalImage);
// 获取原始图像的宽度和高度
$originalWidth = imagesx($original);
$originalHeight = imagesy($original);
// 创建缩略图的GD图像对象
$thumbnail = imagecreatetruecolor($thumbnailWidth, $thumbnailHeight);
// 将原始图像缩小到缩略图大小
imagecopyresampled($thumbnail, $original, 0, 0, 0, 0, $thumbnailWidth, $thumbnailHeight, $originalWidth, $originalHeight);
// 保存缩略图到文件
imagejpeg($thumbnail, $thumbnailImage);
// 创建剪切图的GD图像对象
$cropped = imagecreatetruecolor($croppedWidth, $croppedHeight);
// 计算剪切图的起始位置
$cropX = ($originalWidth - $croppedWidth) / 2;
$cropY = ($originalHeight - $croppedHeight) / 2;
// 将原始图像剪切为指定大小的剪切图
imagecopy($cropped, $original, 0, 0, $cropX, $cropY, $croppedWidth, $croppedHeight);
// 保存剪切图到文件
imagejpeg($cropped, $croppedImage);
// 释放内存
imagedestroy($original);
imagedestroy($thumbnail);
imagedestroy($cropped);
以上代码假设原始图像是JPEG格式,你可以根据实际情况修改代码以适应其他图像格式。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站