图片存储的基本原则

1. 图片格式选择

2. 图片压缩

3. 图片缓存

PHP图片存储实战

1. 使用GD库处理图片

GD库是PHP中处理图像的标准库,支持多种图像格式和丰富的图像处理功能。

代码示例:

<?php
// 加载图片
$image = imagecreatefromjpeg('path/to/image.jpg');

// 调整图片大小
$width = 800;
$height = 600;
$thumbnail = imagecreatetruecolor($width, $height);

// 复制并调整图片大小
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));

// 输出图片
imagejpeg($thumbnail, 'path/to/thumbnail.jpg');

// 释放内存
imagedestroy($image);
imagedestroy($thumbnail);
?>

2. 使用ImageMagick处理图片

ImageMagick是一个功能强大的图像处理库,通过PHP扩展可以轻松集成到PHP项目中。

代码示例:

<?php
// 加载图片
$image = new Imagick('path/to/image.jpg');

// 调整图片大小
$image->resizeimage(800, 600, Imagick::FILTER_LANCZOS, 1);

// 输出图片
$image->writeImage('path/to/thumbnail.jpg');

// 释放内存
$image->clear();
$image->destroy();
?>

3. 使用第三方服务处理图片

代码示例:

<?php
// 使用七牛云处理图片
$accessKey = 'your-access-key';
$secretKey = 'your-secret-key';
$bucket = 'your-bucket';
$domain = 'your-domain';

// 图片上传
$client = new Qiniu\http\Client();
$response = $client->post("https://up-z2.qiniup.com", [
    'file' => new Qiniu\http\FormFile('path/to/image.jpg', 'image/jpeg'),
    'params' => [
        'key' => 'new-image-key.jpg',
    ],
    'headers' => [
        'Authorization' => 'UpToken ' . Qiniu\Auth::buildUpToken($bucket, $accessKey, $secretKey),
    ],
]);

// 图片处理
$client = new Qiniu\http\Client();
$response = $client->get("https://$domain/image/new-image-key.jpg?imageMogr2/thumbnail/800x600");
?>

总结