引言
准备工作
在开始之前,请确保您的PHP环境已安装以下扩展:
- cURL:用于从远程服务器下载文件。
- fileinfo:用于获取文件类型信息。
您可以通过以下命令检查这些扩展是否已安装:
php -m | grep curl
php -m | grep fileinfo
如果扩展未安装,请参考您的PHP安装文档进行安装。
步骤一:下载远程图片
$url = 'https://example.com/image.jpg';
$imageData = file_get_contents($url);
if ($imageData === false) {
die('无法下载图片');
}
$localPath = '/path/to/local/image.jpg';
file_put_contents($localPath, $imageData);
步骤二:生成唯一文件名
function generateUniqueFileName($extension) {
return uniqid() . '.' . $extension;
}
$extension = pathinfo($url, PATHINFO_EXTENSION);
$uniqueFileName = generateUniqueFileName($extension);
步骤三:处理图片
1. 调整图片大小
function resizeImage($image, $newWidth, $newHeight) {
$width = imagesx($image);
$height = imagesy($image);
$ratio = min($newWidth / $width, $newHeight / $height);
$newWidth = $width * $ratio;
$newHeight = $height * $ratio;
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
return $newImage;
}
$image = imagecreatefromjpeg($localPath);
$newImage = resizeImage($image, 800, 600);
imagejpeg($newImage, $localPath);
2. 添加水印
function addWatermark($image, $watermarkText, $fontFile, $fontSize, $color, $position) {
$fontId = imagettftext($image, $fontSize, 0, 10, 10, $color, $fontFile, $watermarkText);
return $image;
}
$fontFile = '/path/to/font.ttf';
$watermarkText = 'Sample Text';
$fontSize = 20;
$color = imagecolorallocate($image, 255, 255, 255);
$position = 'top-left';
$image = addWatermark($image, $watermarkText, $fontFile, $fontSize, $color, $position);
imagejpeg($image, $localPath);