Sometimes you need to add a watermark to a website when uploading an image. The watermark can be divided into a text watermark and an image watermark.
Sometimes you need to add a watermark to a website when uploading an image. The watermark can be divided into a text watermark and an image watermark.
Text watermark
A text watermark adds text to an image. It mainly uses the imagefttext method of the gd library and requires a font file. As follows:
The implementation code is as follows:
The Code is as follows:
$ Dst_path = 'dst.jpg ';
// Create an image instance
$ Dst = imagecreatefromstring (file_get_contents ($ dst_path ));
// Text
$ Font = './simsun. ttc'; // font
$ Black = imagecolorallocate ($ dst, 0x00, 0x00, 0x00); // font color
Imagefttext ($ dst, 13, 0, 20, 20, $ black, $ font, 'happy Project ');
// Output image
List ($ dst_w, $ dst_h, $ dst_type) = getimagesize ($ dst_path );
Switch ($ dst_type ){
Case 1: // GIF
Header ('content-Type: image/gif ');
Imagegif ($ dst );
Break;
Case 2: // JPG
Header ('content-Type: image/jpeg ');
Imagejpeg ($ dst );
Break;
Case 3: // PNG
Header ('content-Type: image/png ');
Imagepng ($ dst );
Break;
Default:
Break;
}
Imagedestroy ($ dst );
Image Watermark
An image watermark is used to add an image to another image, mainly using imagecopy and imagecopymerge of the gd library. As follows:
The implementation code is as follows:
The Code is as follows:
$ Dst_path = 'dst.jpg ';
$ Src_path = 'src.jpg ';
// Create an image instance
$ Dst = imagecreatefromstring (file_get_contents ($ dst_path ));
$ Src = imagecreatefromstring (file_get_contents ($ src_path ));
// Obtain the width and height of the watermark image
List ($ src_w, $ src_h) = getimagesize ($ src_path );
// Copy the watermark image to the target image. The last parameter 50 is to set transparency. The transparency is achieved here.
Imagecopymerge ($ dst, $ src, 10, 10, 0, 0, $ src_w, $ src_h, 50 );
// If the watermark image is transparent, use the imagecopy method.
// Imagecopy ($ dst, $ src, 10, 10, 0, 0, $ src_w, $ src_h );
// Output image
List ($ dst_w, $ dst_h, $ dst_type) = getimagesize ($ dst_path );
Switch ($ dst_type ){
Case 1: // GIF
Header ('content-Type: image/gif ');
Imagegif ($ dst );
Break;
Case 2: // JPG
Header ('content-Type: image/jpeg ');
Imagejpeg ($ dst );
Break;
Case 3: // PNG
Header ('content-Type: image/png ');
Imagepng ($ dst );
Break;
Default:
Break;
}
Imagedestroy ($ dst );
Imagedestroy ($ src );