Home  >  Article  >  Backend Development  >  How to add watermark to images using PHP

How to add watermark to images using PHP

王林
王林Original
2023-08-26 23:48:141375browse

How to add watermark to images using PHP

How to use PHP to add watermarks to pictures

Introduction:
In web development, in order to protect the copyright of pictures and add some personalized effects, we It is often necessary to add watermarks to images. In this article, I will introduce how to use PHP to add watermarks to images and give corresponding code examples.

Step 1: Obtain the path of the image and watermark image
Before adding watermark to the image, we need to obtain the path of the image to be processed and the watermark image. This can be achieved through the following code:

$imgPath = "path/to/image.jpg";  // 待处理图片路径
$watermarkPath = "path/to/watermark.png";  // 水印图片路径

Step 2: Create a new image with a watermark
Next, we need to create a new image and merge the image to be processed and the watermark image into In new pictures. This can be achieved through the following code:

// 获取待处理图片信息
$imgInfo = getimagesize($imgPath); 
$imgWidth = $imgInfo[0];  // 图片宽度
$imgHeight = $imgInfo[1];  // 图片高度

// 创建一个带有水印的新图片
$newImg = imagecreatefromjpeg($imgPath);

// 获取水印图片信息
$wmInfo = getimagesize($watermarkPath);
$wmWidth = $wmInfo[0];  // 水印图片宽度
$wmHeight = $wmInfo[1];  // 水印图片高度

// 计算水印图片在新图片中的位置
$posX = $imgWidth - $wmWidth - 10;  // 水印图片的X坐标
$posY = $imgHeight - $wmHeight - 10;  // 水印图片的Y坐标

// 合并水印图片到新图片中
$watermark = imagecreatefrompng($watermarkPath);
imagecopy($newImg, $watermark, $posX, $posY, 0, 0, $wmWidth, $wmHeight);

Step 3: Output or save a new picture with a watermark
The last step is to output or save a new picture with a watermark, depending on our needs. This can be achieved through the following code:

// 输出带有水印的新图片
header('Content-Type: image/jpeg');
imagejpeg($newImg);

// 或者保存带有水印的新图片
$newImgPath = "path/to/newImage.jpg";  // 保存路径
imagejpeg($newImg, $newImgPath);

// 释放内存
imagedestroy($newImg);
imagedestroy($watermark);

Summary:
Through the above steps, we can easily use PHP to add watermarks to images, protect copyrights, and increase the personalized effect of images. It should be noted that according to the actual situation, we can adjust the position and transparency of the watermark image to achieve the best effect. I hope this article can be helpful to everyone!

The above is the detailed content of How to add watermark to images using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn