function cvimt($imageUrl){
$targetWidth= 500;
$targetHeight =500;
$startY = 0;
return cropImageToSize($imageUrl,$targetWidth,$targetHeight,$startY);
}
function cropImageToSize($imageUrl, $targetWidth, $targetHeight, $startY) {
try {
// 创建cURL句柄
$ch = curl_init($imageUrl);
// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// 执行cURL请求并获取图片数据
$imageData = curl_exec($ch);
// 关闭cURL句柄
curl_close($ch);
// 从图像数据创建图像资源
$image = imagecreatefromstring($imageData);
if (!$image) {
throw new Exception('无法创建图像资源');
}
// 获取原始图像的宽度和高度
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
// 计算等比例缩放后的宽度和高度
$ratio = min($originalWidth / $targetWidth, ($originalHeight - $startY) / $targetHeight); // 除去起始点的高度
$scaledWidth = $targetWidth * $ratio;
$scaledHeight = $targetHeight * $ratio;
// 计算剪辑起始点的X坐标和Y坐标
$startX = ($originalWidth - $scaledWidth) / 2;
$startY = $startY; // 从指定Y坐标开始裁剪
// 创建新的图像资源
$newImage = imagecreatetruecolor($targetWidth, $targetHeight);
// 将原始图像复制到新图像中(使用imagecopyresampled进行重采样)
if (!imagecopyresampled($newImage, $image, 0, 0, $startX, $startY, $targetWidth, $targetHeight, $scaledWidth, $scaledHeight)) {
throw new Exception('无法复制图像');
}
// 保存新图像(调整第三个参数为90,降低输出图像的压缩质量)
$root_rul = '/uploads/thumbnail/' . rand(1000,9999).'.jpg';
$newImagePath = ROOT_PATH.'public/' .$root_rul;
if (!imagejpeg($newImage, $newImagePath, 90)) {
throw new Exception('无法保存图像');
}
// 销毁图像资源
imagedestroy($image);
imagedestroy($newImage);
return $root_rul;
} catch (Exception $e) {
error_log($e->getMessage());
return false;
}
}
本文共 个字数,平均阅读时长 ≈ 分钟,您已阅读:0时0分0秒。
649494848