引言

图片下载与保存

1. 确保CURL扩展已安装

php -m | grep curl

如果返回结果中包含 “curl”,则表示CURL扩展已安装;如果没有返回结果,则需要安装CURL扩展。

2. 使用file_get_contents()获取远程图片内容

function downloadImage($url, $savePath) {
    $imageContent = file_get_contents($url);
    if ($imageContent !== false) {
        file_put_contents($savePath, $imageContent);
        return true;
    } else {
        return false;
    }
}

3. 生成唯一的文件名

为了防止文件名冲突,我们可以使用uniqid()函数生成唯一的文件名。以下是一个示例代码:

function generateUniqueFileName($extension) {
    return uniqid() . '.' . $extension;
}

4. 创建保存目录

function createDirectory($dirPath) {
    if (!file_exists($dirPath)) {
        mkdir($dirPath, 0755, true);
    }
}

5. 图片下载与保存流程

$url = 'https://example.com/image.jpg';
$savePath = '/var/www/images/';
$extension = pathinfo($url, PATHINFO_EXTENSION);

createDirectory($savePath);
$uniqueFileName = generateUniqueFileName($extension);
$fullSavePath = $savePath . $uniqueFileName;

downloadImage($url, $fullSavePath);

图片优化

1. 使用GD库处理图片

function resizeImage($imagePath, $newWidth, $newHeight) {
    list($width, $height) = getimagesize($imagePath);
    $aspectRatio = $width / $height;

    if ($newWidth / $newHeight > $aspectRatio) {
        $newWidth = $newHeight * $aspectRatio;
    } else {
        $newHeight = $newWidth / $aspectRatio;
    }

    $image = imagecreatetruecolor($newWidth, $newHeight);
    $sourceImage = imagecreatefromjpeg($imagePath);
    imagecopyresampled($image, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    imagejpeg($image, $imagePath);
    imagedestroy($image);
    imagedestroy($sourceImage);
}

2. 使用ImageMagick库处理图片

function resizeImageWithImagick($imagePath, $newWidth, $newHeight) {
    $image = new Imagick($imagePath);
    $image->resizeImage($newWidth, $newHeight, Imagick::FILTER_LANCZOS, 1);
    $image->writeImage($imagePath);
}

总结