引言

文件流技术简介

安装GD库

# 安装GD库
sudo apt-get install php-gd

创建图像资源

// 创建一个空白画布
$width = 500;
$height = 500;
$image = imagecreatetruecolor($width, $height);

// 分配颜色
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);

// 填充画布
imagefill($image, 0, 0, $white);

加载图片

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

图片操作

在图像资源上可以进行各种操作,如调整大小、旋转、裁剪等。

// 调整图片大小
list($sourceWidth, $sourceHeight) = getimagesize($sourceImage);
$targetWidth = 300;
$targetHeight = ($sourceHeight * $targetWidth) / $sourceWidth;

$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);

保存图片

// 保存图片
imagejpeg($targetImage, 'path/to/processed_image.jpg');

高效利用文件流

// 使用文件流读取图片
$sourcePath = 'path/to/image.jpg';
$sourceData = fopen($sourcePath, 'rb');
$sourceImage = imagecreatefromjpeg($sourceData);

// 使用文件流写入图片
$targetPath = 'path/to/processed_image.jpg';
$targetData = fopen($targetPath, 'wb');
imagejpeg($targetImage, $targetData);
fclose($targetData);

总结