PHP Image Processing Using imagecopy Function to Add Image Watermarking Example

  • 2021-08-05 09:06:28
  • OfStack

Adding watermarks to pictures is also a common function in picture processing. Because all the pictures you see on the page can be easily obtained, and the pictures you have worked so hard to edit can be used without being easily taken away by others, so add watermarks to the pictures to determine the copyright and prevent them from being stolen. Making watermark can use text (company name plus website), can also use pictures (company LOGO), picture watermark effect is better 1, because can be done through 1 picture software beautification. To use text as watermark, you only need to draw some text on the picture. If you make a picture watermark, you need to first understand the imagecopy () function in the GD library, which can copy 1 part of the picture. The prototype of this function is as follows:


bool imagecopy(resource dst_im,resource src_im,int dst_x,int dst_y,int src_x,int src_y,int src_w,int src_h)

This function copies a part of the src_im image with coordinates starting from src_x, src_y, width src_w, and height src_h to the coordinates dst_x and dst_y in the dst_im image. Take the picture in JPEG format as an example, write a function watermark () to add watermark to the picture, and the code is as follows:


<?php
// Add a picture watermark (random position) to the background picture in the format of jpeg The format of the watermark image is gif
function watermark($filename,$water){
// Gets the width and height of the background picture
list($b_w,$b_h) = getimagesize($filename);
// Gets the width and height of the watermark image
list($w_w,$w_h) = getimagesize($water);
// Random starting position of watermark picture in background picture
$posX = rand(0, ($b_w-$w_w));
$posY = rand(0, ($b_h-$w_h));
// Create resources for background pictures
$back = imagecreatefromjpeg($filename);
// Resources for creating watermarked pictures
$water = imagecreatefromgif($water);
// Use imagecopy() Function to copy the watermark image to the location specified by the background image
imagecopy($back, $water, $posX, $posY, 0, 0, $w_w, $w_h);
// Save the background picture with the watermarked picture
imagejpeg($back,$filename);
imagedestroy($back);
imagedestroy($water);
}
watermark("brophp.jpg", "logo.gif");
?>


Related articles: