欢迎访问宙启技术站
智能推送

PHP图像处理函数全覆盖,让你的图片处理得心应手

发布时间:2023-06-29 21:40:23

PHP是一种流行的服务器端脚本语言,用于开发动态网站和应用程序。在开发过程中,图像处理是一个常见的需求,无论是缩放、剪裁、旋转、水印、滤镜等操作,PHP都提供了一系列的内置函数和扩展来满足这些需求。本文将对PHP的图像处理函数进行全覆盖介绍,让你的图片处理得心应手。

1. 图像创建与导出

在PHP中,可以使用imagecreate()函数创建一个空白的图像资源,并使用imagepng()imagegif()imagejpeg()等函数将图像导出为不同的格式。

// 创建一个宽度为200,高度为100的空白图像
$image = imagecreate(200, 100);

// 导出图像为PNG格式,并保存为example.png
imagepng($image, 'example.png');

// 释放图像资源
imagedestroy($image);

2. 图像读取与复制

除了创建空白图像,还可以使用imagecreatefrompng()imagecreatefromgif()imagecreatefromjpeg()等函数读取已有图像的资源,并使用imagecopy()imagecopyresampled()等函数将图像复制到其他图像上。

// 读取example.png
$source = imagecreatefrompng('example.png');

// 创建一个宽度为400,高度为200的空白图像
$target = imagecreate(400, 200);

// 将目标图像上复制源图像的一部分
imagecopy($target, $source, 0, 0, 50, 50, 100, 100);

// 导出目标图像为PNG格式,并保存为result.png
imagepng($target, 'result.png');

// 释放图像资源
imagedestroy($source);
imagedestroy($target);

3. 图像缩放与剪裁

在PHP中,可以使用imagescale()函数对图像进行缩放,使用imagecrop()函数对图像进行剪裁。

// 读取example.png
$image = imagecreatefrompng('example.png');

// 缩放图像为宽度为200,高度为100
$scale = imagescale($image, 200, 100);

// 导出缩放后的图像为JPEG格式,并保存为scaled.jpg
imagejpeg($scale, 'scaled.jpg');

// 剪裁图像为宽度为100,高度为100
$crop = imagecrop($image, ['x' => 50, 'y' => 50, 'width' => 100, 'height' => 100]);

// 导出剪裁后的图像为JPEG格式,并保存为cropped.jpg
imagejpeg($crop, 'cropped.jpg');

// 释放图像资源
imagedestroy($image);
imagedestroy($scale);
imagedestroy($crop);

4. 图像旋转与翻转

使用imagerotate()函数可以对图像进行旋转,通过设置旋转角度和背景颜色,可以实现顺时针、逆时针旋转、镜像翻转等效果。

// 读取example.png
$image = imagecreatefrompng('example.png');

// 顺时针旋转90度
$rotate = imagerotate($image, 90, 0);

// 导出旋转后的图像为JPEG格式,并保存为rotated.jpg
imagejpeg($rotate, 'rotated.jpg');

// 水平镜像翻转
$flip = imageflip($image, IMG_FLIP_HORIZONTAL);

// 导出翻转后的图像为JPEG格式,并保存为flipped.jpg
imagejpeg($flip, 'flipped.jpg');

// 释放图像资源
imagedestroy($image);
imagedestroy($rotate);
imagedestroy($flip);

5. 图像添加水印

可以使用imagecopy()或者imagettftext()函数在图像上添加文本水印,使用imagecopy()函数在图像上添加图像水印。

// 读取example.png
$image = imagecreatefrompng('example.png');

// 添加文本水印
$text_color = imagecolorallocate($image, 255, 255, 255);
imagettftext($image, 20, 0, 50, 50, $text_color, 'font.ttf', 'Watermark');

// 添加图像水印
$watermark = imagecreatefrompng('watermark.png');
imagecopy($image, $watermark, 0, 0, 0, 0, imagesx($watermark), imagesy($watermark));

// 导出带水印的图像为JPEG格式,并保存为watermarked.jpg
imagejpeg($image, 'watermarked.jpg');

// 释放图像资源
imagedestroy($image);
imagedestroy($watermark);

6. 图像滤镜效果

在PHP中,可以使用imagefilter()函数对图像应用不同的滤镜效果,如灰度、浮雕、模糊、锐化等。

// 读取example.png
$image = imagecreatefrompng('example.png');

// 灰度滤镜
imagefilter($image, IMG_FILTER_GRAYSCALE);

// 浮雕滤镜
imagefilter($image, IMG_FILTER_EMBOSS);

// 导出滤镜后的图像为JPEG格式,并保存为filtered.jpg
imagejpeg($image, 'filtered.jpg');

// 释放图像资源
imagedestroy($image);

综上所述,PHP提供了丰富的图像处理函数和扩展,可以满足各种图像处理需求。无论是创建与导出图像、图像读取与复制、图像缩放与剪裁、图像旋转与翻转、图像添加水印、图像滤镜效果等操作,PHP都有相应的函数来实现。掌握这些函数的使用,能够让你的图片处理得心应手。