图片保存

用户上传图片

if ($_FILES['image']['error'] == UPLOAD_ERR_OK) {
    $tempFile = $_FILES['image']['tmp_name'];
    $targetPath = 'path/to/save/image.png';
    move_uploaded_file($tempFile, $targetPath);
}

在这个示例中,$_FILES['image']是用户上传的文件信息数组。move_uploaded_file()函数接受两个参数,第一个是临时文件路径,第二个是目标文件路径。

远程图片保存

$remoteImage = 'http://example.com/image.jpg';
$localPath = 'path/to/save/image.jpg';

$ch = curl_init($remoteImage);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$remoteImageContent = curl_exec($ch);
curl_close($ch);

file_put_contents($localPath, $remoteImageContent);

图片处理

PHP提供了ImageCreate()ImageCreateFromXXX()函数来创建和操作图像资源。以下是一些基本的图像处理步骤:

创建图像资源

$width = 100;
$height = 100;
$canvas = imagecreatetruecolor($width, $height);

在这个示例中,创建了一个100x100的透明背景画布。

分配颜色

$red = imagecolorallocate($canvas, 255, 0, 0);

在这个示例中,分配了一个红色颜色。

填充画布

imagefill($canvas, 0, 0, $red);

在这个示例中,使用红色填充了整个画布。

保存图像

imagepng($canvas, 'path/to/save/image.png');

在这个示例中,将图像保存为PNG文件。

图片显示

<img src="path/to/save/image.png" alt="Image">

总结