PHP and GD library tutorial: How to add blur effects to images
Overview:
In web development, images often need to be processed, one of which is to add blur effects. PHP provides a powerful GD library that allows us to easily blur images. This tutorial will show you how to add a blur effect to an image using PHP and the GD library, with code examples.
Step 1: Set up the GD library
To use the GD library, we need to ensure that PHP has enabled the GD library. You can check whether the GD library has been enabled through the following code:
if (function_exists('gd_info')) { echo "GD库已启用"; } else { echo "GD库未启用"; }
Step 2: Open the original image
To add a blur effect to the image, you first need to open the original image. Use the imagecreatefromjpeg()
function in PHP to open images in JPEG format, and use the imagecreatefrompng()
function to open images in PNG format. The following is a sample code for opening an image:
$sourceImage = imagecreatefromjpeg('source.jpg'); // 替换为你自己的原始图片路径
Step 3: Create a blurred image
After opening the original image, we can use the GD library function imagefilter()
to add a blur effect to the image . The following is a sample code for creating a blurred image:
imagefilter($sourceImage, IMG_FILTER_GAUSSIAN_BLUR);
Step 4: Save the blurred image
After adding the blur effect, we need to save the blurred image to a specified location. Use the GD library function imagejpeg()
to save the image in JPEG format, and use imagepng()
to save the image in PNG format. The following is a sample code for saving blurry images:
imagejpeg($sourceImage, 'blur.jpg'); // 替换为你自己的保存路径
The complete sample code is as follows:
if (function_exists('gd_info')) { echo "GD库已启用"; $sourceImage = imagecreatefromjpeg('source.jpg'); // 替换为你自己的原始图片路径 imagefilter($sourceImage, IMG_FILTER_GAUSSIAN_BLUR); imagejpeg($sourceImage, 'blur.jpg'); // 替换为你自己的保存路径 imagedestroy($sourceImage); } else { echo "GD库未启用"; }
Notes:
extension=gd
statement in the php.ini file. If it cannot be found, add extension=gd
and restart the server. Conclusion:
In this tutorial, we learned how to add a blur effect to an image using PHP and the GD library. With a few simple lines of code, we can blur images. I believe that by studying this tutorial, you can easily apply this technology in web development and adjust the parameters as needed to achieve the results you want.
The above is the detailed content of PHP and GD Library Tutorial: How to Add Blur Effect to Images. For more information, please follow other related articles on the PHP Chinese website!