Home > Backend Development > PHP Tutorial > Add watermark to image with PHP imagecopy() and imagecopymerge()_PHP Tutorial

Add watermark to image with PHP imagecopy() and imagecopymerge()_PHP Tutorial

WBOY
Release: 2016-07-13 10:46:16
Original
1049 people have browsed it

There are many ways to add watermarks to images in PHP. These functions are all based on the GD library in PHP. If you do not have an account with the GD library, you cannot use the watermark function.

The imagecopymerge() function is used to copy and merge part of an image. It returns TRUE if successful, otherwise it returns FALSE.

Enable PHP GD library support under Windows

Find php.ini, open the content and find:

;extension=php_gd2.dll

Remove the first semicolon ";" and save it. If there is no semicolon in the first place, it means it is already enabled

Basic syntax

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

Parameter Description: Parameter Description

dst_im target image
src_im copied source image
dst_x target image start x coordinate
dst_y is the starting y coordinate of the target image. If x and y are both 0, it starts from the upper left corner
src_x copy image start x coordinate
src_y starts copying the y coordinate of the image. If x and y are both 0, then copy starts from the upper left corner
src_w (starting from src_x) Width of copy
src_h (starting from src_y) height of copy
pct Image merging degree, value 0-100. When pct=0, nothing is actually done, otherwise it is completely merged.

When pct = 100, this function is exactly the same as imagecopy() for palette images

After knowing how to use it, it is easy to implement our function. You can easily implement it with the following code

The code is as follows Copy code

header("Content-type: image/jpeg");

//original image
$dst = "images/flower_1.jpg";

//Get original image information
$dst_im = imagecreatefromjpeg($dst);
$dst_info = getimagesize($dst);

//Watermark image
$src = "images/logo.gif";
$src_im = imagecreatefromgif($src);
$src_info = getimagesize($src);

//Watermark transparency
$alpha = 30;

//Merge watermark images
imagecopymerge($dst_im,$src_im,$dst_info[0]-$src_info[0],$dst_info[1]-$src_info[1],0,0,$src_info[0],
$src_info[1],$alpha);

//Output the merged watermark image
imagejpeg($dst_im);
imagedestroy($dst_im);
imagedestroy($src_im);
?>

After the new version, the imagecopymerge function is almost no longer used. We can directly use imagecopy to generate watermarks. The functions of the two functions are exactly the same.

//增加水印
$watermark   =1;
$watertype   =2;
$waterstring =''; 
$waterimg="z.png";    //水印图片
$sFilePath ='aa.jpg';
if($watermark==1)
{
 $image_size = getimagesize($sFilePath); //上传的图片
 $water_size = getimagesize($waterimg);  //水印图片
 $iinfo=getimagesize($sFilePath,$iinfo);
 $nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
 $white=imagecolorallocate($nimage,255,255,255);
 $black=imagecolorallocate($nimage,0,0,0);
 $red=imagecolorallocate($nimage,255,0,0);
 imagefill($nimage,0,0,$white);
 switch ($iinfo[2])
 {
  case 1:
   $simage =imagecreatefromgif($sFilePath);
   break;
  case 2:
   $simage =imagecreatefromjpeg($sFilePath);
   break;
  case 3:
   $simage =imagecreatefrompng($sFilePath);
   break;
//            case 6:
//            $simage =imagecreatefromwbmp($sFilePath);
//            break;
  default:
   die("不支持的文件类型");
   exit;
 }
 
 imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
 
 switch($watertype)
 {
  case 1:   //加水印字符串
   imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
   break;
  case 2:   //加水印图片
   $simage1 =imagecreatefrompng($waterimg);     
   $x= $image_size[0]-$water_size[0];
   $y= $image_size[1]-$water_size[1];
   imagecopy($nimage,$simage1,$x,$y,0,0,240,65);
   imagedestroy($simage1);
   break;
 }
    
 switch ($iinfo[2])
 {
  case 1:
   imagegif($nimage, $sFilePath);
//            imagejpeg($nimage, $sFilePath);
   break;
  case 2:
   imagejpeg($nimage, $sFilePath);
   break;
  case 3:
   imagepng($nimage, $sFilePath);
   break;
//            case 6:
//            imagewbmp($nimage, $sFilePath);
//            //imagejpeg($nimage, $sFilePath);
//            break;
 }
 
 //覆盖原上传文件
 imagedestroy($nimage);
 imagedestroy($simage);
}

A better function that can generate thumbnails and add watermarks to pictures


/***
Want to manipulate pictures
First, you must get the size and type information of the image

Watermark: Copy the specified watermark to the target and add a transparent effect

Thumbnail: Copy a large image to a small screen
***/

The code is as follows Copy code

class ImageTool {
// imageInfo analyzes image information
// return array()
Public static function imageInfo($image) {
// Determine whether the picture exists
If (!file_exists($image)) {
                  return false;                                                                                                                                             
$info = getimagesize($image);

If ($info == false) {
                  return false;                                                                                                                                             
//At this time, the info is analyzed and it is an array
         $img['width'] = $info[0];
         $img['height'] = $info[1];
         $img['ext'] = substr($info['mime'], strpos($info['mime'], '/') + 1);

          return $img;                              }  

/*
Watermark function
Parm String $dst and other operation pictures
Parm String $water watermark image
Parm String $save, if not filled in, the original image will be replaced by default
*/
Public static function water($dst, $water, $save = NULL, $pos = 2, $alpha = 50) {
// Make sure 2 pictures exist first
If (!file_exists($dst) || !file_exists($water)) {
                  return false;                                                                                                                                             
// First, make sure the watermark cannot be larger than the image to be operated
         $dinfo = self::imageInfo($dst);
              $wininfo = self::imageInfo($water);                                    
If ($winfo['height'] > $dinfo['height'] || $winfo['width'] > $dinfo['width']) {
                  return false;                                                                                                                                             
// Two pictures, read them on the canvas! But the pictures may be png or jpeg, what function should be used to read them?
$dfunc = 'imagecreatefrom' . $dinfo['ext'];
$wfunc = 'imagecreatefrom' . $winfo['ext'];

If (!function_exists($dfunc) || ​​!function_exists($wfunc)) {
                  return false;                                                                                                                                             
// Dynamically load functions to create canvas
          $dim = $dfunc($dst);
//Create the canvas to be operated
$wim = $wfunc($water);
//Create watermark canvas

// Calculate the pasted coordinates based on the location of the watermark
switch($pos) {
case 0 :
// Upper left corner
$posx = 0;
$posy = 0;
                break; 
 
            case 1 : 
                // 右上角 
                $posx = $dinfo['width'] - $winfo['width']; 
                $posy = 0; 
                break; 
 
            case 3 : 
                // 左下角 
                $posx = 0; 
                $posy = $dinfo['height'] - $winfo['height']; 
                break; 
 
            default : 
                $posx = $dinfo['width'] - $winfo['width']; 
                $posy = $dinfo['height'] - $winfo['height']; 
        } 
 
        // 加水印 
        imagecopymerge($dim, $wim, $posx, $posy, 0, 0, $winfo['width'], $winfo['height'], $alpha); 
 
        // 保存 
        if (!$save) { 
            $save = $dst; 
            unlink($dst); 
            // 删除原图 
        } 
 
        $createfunc = 'image' . $dinfo['ext']; 
        $createfunc($dim, $save); 
 
        imagedestroy($dim); 
        imagedestroy($wim); 
 
        return true; 
    } 
 
    /**
Thumb Generate thumbnail
Scale proportionally, leave blank on both sides
**/ 
    public static function thumb($dst, $save = NULL, $width = 200, $height = 200) { 
        // 首先判断待处理的图片存不存在 
        $dinfo = self::imageInfo($dst); 
        if ($dinfo == false) { 
            return false; 
        } 
 
        // 计算缩放比例 
        $calc = min($width / $dinfo['width'], $height / $dinfo['height']); 
 
        // 创建原始图的画布 
        $dfunc = 'imagecreatefrom' . $dinfo['ext']; 
        $dim = $dfunc($dst); 
 
        // 创建缩略画布 
        $tim = imagecreatetruecolor($width, $height); 
 
        // 创建白色填充缩略画布 
        $white = imagecolorallocate($tim, 255, 255, 255); 
 
        // 填充缩略画布 
        imagefill($tim, 0, 0, $white); 
 
        // 复制并缩略 
        $dwidth = (int)$dinfo['width'] * $calc; 
        $dheight = (int)$dinfo['height'] * $calc; 
 
        $paddingx = (int)($width - $dwidth) / 2; 
        $paddingy = (int)($height - $dheight) / 2; 
 
        imagecopyresampled($tim, $dim, $paddingx, $paddingy, 0, 0, $dwidth, $dheight, $dinfo['width'],

$dinfo['height']); 
 
        // 保存图片 
        if (!$save) { 
            $save = $dst; 
            unlink($dst); 
        } 
 
        $createfunc = 'image' . $dinfo['ext']; 
        $createfunc($tim, $save); 
 
        imagedestroy($dim); 
        imagedestroy($tim); 
 
        return true; 
 
    } 
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/632955.htmlTechArticle图像添加水印在php中有很多种办法可以实现,他这些功能都是基于php中的GD库的,如果没有开户GD库是不可以使用水印功能的。 imagecopymerge...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template