PHP常用图像处理函数总结及实战
发布时间:2023-06-04 08:27:14
PHP作为一种流行的Web开发语言,可以很方便地实现图像处理功能。本文将对PHP常用的图像处理函数进行总结,并探讨一些实际应用。
1. imagecreatetruecolor函数
创建一个新的真彩色图像,返回一个图像标识符。可用于创建一个白色背景的画布:
$width = 500; $height = 500; $image = imagecreatetruecolor($width, $height); $bgColor = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bgColor);
2. imagecopyresampled函数
按比例缩放、裁剪、复制一幅图像到另一个图像。
$srcImg = 'source.jpg'; $dstImg = 'destination.jpg'; $dstWidth = 200; $dstHeight = 200; $srcInfo = getimagesize($srcImg); $srcWidth = $srcInfo[0]; $srcHeight = $srcInfo[1]; $srcImgType = $srcInfo[2]; $srcImage = imagecreatefromjpeg($srcImg); $dstImage = imagecreatetruecolor($dstWidth, $dstHeight); imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $dstWidth, $dstHeight, $srcWidth, $srcHeight); imagejpeg($dstImage, $dstImg);
此段代码将目标图片缩放到一定大小。
3. imagecopy函数
将一个图像拷贝到另一个图像
//创建背景画布 $width = 500; $height = 500; $image = imagecreatetruecolor($width, $height); $bgColor = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bgColor); //将logo拷贝到画布上 $logoImg = 'logo.png'; $srcInfo = getimagesize($logoImg); $logoWidth = $srcInfo[0]; $logoHeight = $srcInfo[1]; $logoImgType = $srcInfo[2]; $srcImage = imagecreatefrompng($logoImg); imagecopy($image, $srcImage, 50, 50, 0, 0, $logoWidth, $logoHeight);
此段代码将一个logo拷贝到制定的区域内。
4. imagecolorallocate函数
给图像分配一种颜色
$color = imagecolorallocate($image, 255, 0, 0);
此段代码将创建一种红色的颜色。
5. imagerotate函数
旋转一幅图像
$srcImg = 'source.jpg'; $dstImg = 'destination.jpg'; $srcImage = imagecreatefromjpeg($srcImg); $dstImage = imagerotate($srcImage, 45, 0); imagejpeg($dstImage, $dstImg);
此段代码将图像旋转45度。
以上是PHP中常用的图像处理函数,我们可以根据不同的需求结合上述函数进行编程,具体应用如下:
1. 图片加水印
我们可以添加一个透明的PNG水印图像来防止图片被盗用。以下是示例:
// Load the two images
$background = imagecreatefromjpeg('background.jpg');
$watermark = imagecreatefrompng('watermark.png');
// Set the margins for the watermark
$marge_right = 10;
$marge_bottom = 10;
// Get the dimensions of the watermark image
$sx = imagesx($watermark);
$sy = imagesy($watermark);
// Copy the watermark image onto the background image
imagecopy($background, $watermark, imagesx($background) - $sx - $marge_right, imagesy($background) - $sy - $marge_bottom, 0, 0, imagesx($watermark), imagesy($watermark));
// Output the results
header('Content-Type: image/jpeg');
imagejpeg($background);
2. 批量缩放图片
我们可以使用PHP来批量缩放图片,以便在浏览器中更快地下载页面。以下是示例:
$dir = '/path/to/images';
$dirHandle = opendir($dir);
while (($file = readdir($dirHandle)) !== false) {
$filename = $dir . '/' . $file;
if (is_file($filename)) {
list($width, $height, $type, $attr) = getimagesize($filename);
if ($width > 1024 || $height > 768) {
$image = imagecreatefromjpeg($filename);
imagejpeg($image, $filename, 80);
}
}
}
closedir($dirHandle);
以上就是常见的PHP图像处理函数及实战总结,当然,实际应用场景还有很多,读者可根据自己的需求进行编程。
