引言

第一章:PHP图片流处理基础

1.1 PHP中处理图片的方法

  • imagecreatefromjpeg(): 从JPEG文件创建图像。
  • imagecreatefrompng(): 从PNG文件创建图像。
  • imagecreatefromgif(): 从GIF文件创建图像。
  • imagecreatetruecolor(): 创建一个图像资源,并返回一个真彩色图像。
  • imagecopyresampled(): 复制图像的一部分到另一个图像资源。

1.2 图片流处理的概念

第二章:PHP图片处理实战

2.1 图片上传与保存

<?php
if ($_FILES['image']['error'] == 0) {
    $image = $_FILES['image']['tmp_name'];
    $destination = 'uploads/' . basename($_FILES['image']['name']);

    if (move_uploaded_file($image, $destination)) {
        echo "文件已成功上传到 " . $destination;
    } else {
        echo "上传失败";
    }
}
?>

2.2 图片缩放

<?php
$image = imagecreatefromjpeg('path/to/image.jpg');
$width = 200;
$height = 200;

$thumbnail = imagecreatetruecolor($width, $height);
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));

imagejpeg($thumbnail, 'path/to/thumbnail.jpg');
?>

2.3 图片裁剪

<?php
$image = imagecreatefromjpeg('path/to/image.jpg');
$width = 200;
$height = 200;

$crop = imagecrop($image, ['x' => 50, 'y' => 50, 'width' => $width, 'height' => $height]);
imagejpeg($crop, 'path/to/cropped.jpg');
?>

第三章:高级图片处理技巧

3.1 图像滤镜与效果

PHP提供了多种图像滤镜和效果,如灰度、模糊、亮度调整等。以下是一个使用imagefilter()函数添加模糊效果的示例:

<?php
$image = imagecreatefromjpeg('path/to/image.jpg');
imagefilter($image, IMG_FILTER_BLUR);
imagejpeg($image, 'path/to/filtered.jpg');
?>

3.2 图像水印

<?php
$watermark = imagecreatefrompng('path/to/watermark.png');
$image = imagecreatefromjpeg('path/to/image.jpg');
$width = imagesx($image);
$height = imagesy($image);

imagecopy($image, $watermark, $width - 50, $height - 50, 0, 0, imagesx($watermark), imagesy($watermark));
imagejpeg($image, 'path/to/image_with_watermark.jpg');
?>

结论