PHP Implementation Watermark effect (text, picture)

Source: Internet
Author: User
Tags explode getcolor image identifier imagecopy imagejpeg transparent color strcmp unsupported

First Kind
<?php/** *  function: Add watermark effect  *       $i   image to add watermark effect to a picture  *        $t   Watermark text  *       $size   Text Size  *       $pos   Location of Watermark  *       $color   Text color  *       $flag   is a Boolean value that is used to distinguish between a watermark on the original image  *        $type   If $flag equals false  the watermark is added to the new map   The new file name is   formerly _txt.jpg */function txt ( $i, $t = ' All rights reserved ', $size =25, $pos =5, $color = ' Rand ', $flag =true, $type = ' _txt ') {   $img  =  Imagecreatefromjpeg ($i);   $w  = imagesx ($img);   $h  = imagesy ($img);    $font  = dirname (__file__). ' /font/ls.ttf ';   $ps  = imagettfbbox ($size, 0, $font, $t);   $tw  =  $ps [4];    $th  = abs ($ps [5]);   switch ($pos) {    case 1:bReak;      case 2:break;      case 3: Break;      case 4:break;      case 5: $x = ($w-$TW)/2; $y = ($h-$th)/2+ $th;break;      case 6:break;       case 7:break;      case 8:break;       case 9:break;      default:break;  }    $c  = getcolor ($img, $color);   imagettftext ($img, $size, 0, $x, $y, $c, $font, $t);   if ($flag) {    imagejpeg ($img, $i);    }else{    $ Ext = ext ($i);     $ppp  = rtrim ($i, '. '. $ext);     $ppp  =  $ppp. $type. $ext;     imagejpeg ($img, $PPP);   }}  function getcolor ($i, $c = ' rand ', $a =50) {   $cc  =  ';   switch ($c) {    case  ' white ': $cc =imagecolorallocatealpha ($i, 255,255,255, $a);break;    case  ' black ': $CC = Imagecolorallocatealpha ($i, 0,0,0, $a);break;    case  ' red ': $cc =imagecolorallocatealpha ($i, 255,0,0, $a);break;    case  ' green ': $cc =imagecolorallocatealpha ($i, 0,255,0, $a); break;    case  ' Blue ': $cc =imagecolorallocatealpha ($i, 0,0,255, $a);break;     case  ' Orange ': $cc =imagecolorallocatealpha ($i, 0xff,0x66,0x33, $a);break;     case  ' yellow ': $cc =imagecolorallocatealpha ($i, 255,255,0, $a);break;    case  ' Rand ': $CC =imagecolorallocatealpha ($i, Mt_rand (0,255), Mt_rand (0,255), Mt_rand (0,255), $a);break;     default:       $cs  = substr ($c, 1);        $ok  = str_split ($cs,2);       $cc  = imagecolorallocatealpha ($i, Hexdec ($ok [0]), Hexdec ($ok [ 1]), Hexdec ($ok [2]), $a);     break;     }  return $ CC;}     /** *  function: Returns the extension  */  function ext ($f) {   $exts  = explode ('. ', $f);   return end ($exts);}   /** *  function is: Return file name, without extension  */function name ($f) {   $s  = explode (' /', $f);   $fn  = end ($s),   return rtrim ($FN, '. '). Ext ($f));}
The second Kind

Let's take another look. Supports adding watermarks to images in both image and text ways. Image support Gif,png,jpg Three formats, watermark image support PNG and GIF

Function setwater ($IMGSRC, $MARKIMG, $markText, $TextColor, $markPos, $fontType, $markType) {   $ srcinfo =  @getimagesize ($IMGSRC);   $srcImg _w  =  $srcInfo [0];  $ srcimg_h  =  $srcInfo [1];       switch  ($srcInfo [2])    {     case 1:        $SRCIM  =imagecreatefromgif ($IMGSRC);       break;      case 2:        $srcim  =imagecreatefromjpeg ($IMGSRC);        break;     case 3:         $srcim  =imagecreatefrompng ($IMGSRC);       break;      default:       die ("Unsupported picture File type");       &nbSp;exit;   }       if (!strcmp ($markType, "img"))   {     if (!file_exists ($markImg)  | |  empty ($MARKIMG))     {      return;     }            $markImgInfo  = @ GetImageSize ($MARKIMG);     $markImg _w  =  $markImgInfo [0];      $MARKIMG _h  =  $markImgInfo [1];            if ($srcImg _w <  $markImg _w | |   $SRCIMG _h <  $markImg _h)     {      return;     }           switch  ($ MARKIMGINFO[2])      {       case 1:           $markim  =imagecreatefromgif ($MARKIMG);          break;       case 2:           $markim  =imagecreatefromjpeg ($MARKIMG);          break;       case 3:           $markim  =imagecreatefrompng ($MARKIMG);         break;        default:         die (" Unsupported watermark picture file type ");          exit;     }             $logow  =  $markImg _w;      $logoh  =  $markImg _h;  }       if (!strcmp ($ Marktype, "text"))  &nbsP {     $fontSize  = 16;    if (!empty ($markText))      {      if (!file_exists ($fontType))        {        return;      }     }    else {      return;     }            $box  =  @imagettfbbox ( $fontSize, 0,  $fontType, $markText);     $logow  = max ($box [2],  $box [4])  - min ($box [0],  $box [6]);     $logoh  = max ($box [1],  $box [3])  - min ($box [5],  $box [7]);   }       if ($markPos  == 0)   {     $markPos  = rand (1, 9);  }         switch ($markPos)   {    case 1:        $x  = +5;       $y  = +5;       break;    case 2:       $x  =  ($srcImg _w  -  $logow)  / 2;       $y  = +5;       break;    case 3:       $x  =   $SRCIMG _w -  $logow  - 5;       $y  = +15;       break;    case 4:       $x  = +5;       $y  =  ($srcImg _h -  $logoh)  /  2;      break;    case 5:        $x  =  ($srcimg_w -  $logow)  / 2;       $y  =  ($srcImg _h  -  $logoh)  / 2;      break;    case 6:        $x  =  $srcImg _w -  $logow  - 5;        $y  =  ($srcImg _h -  $logoh)  / 2;       break;    case 7:       $x  = +5;        $y  =  $srcImg _h -  $logoh  - 5;       break;    case 8:       $x   =  ($srcImg _w -  $logow)  / 2;       $y  =  $srcImg _h -  $logoh  - 5;      break;    case  9:       $x  =  $srcImg _w -  $logow  - 5;      $ y =  $srcImg _h -  $logoh  -5;      break;     default:       die ("This location does not support");        exit;  }        $DST _img = @ Imagecreatetruecolor ($srcImg _w,  $srcImg _h);       imagecopy  (   $DST _img,  $srcim, 0, 0, 0, 0,  $srcImg _w,  $srcImg _h);        if (!strcmp ($markType, "img"))   {    imagecopy ($dst _ img,  $markim,  $x,  $y, 0, 0,  $logow,  $logoh);     Imagedestroy ($markim);   }       if (!strcmp ($markType, "text"))   {     $rgb  = eXplode (', ',  $TextColor);            $color  =  imagecolorallocate ($dst _img,  $rgb [0],  $rgb [1],  $rgb [2]);     Imagettftext ($dst _img,  $fontSize, 0,  $x,  $y,  $color,  $fontType, $markText);   }       switch  ($srcInfo [2])    {      case 1:      imagegif ($dst _img,  $IMGSRC);        break;     case 2:        imagejpeg ($dst _img,  $IMGSRC);       break;      case 3:       imagepng ($DST _img,  $IMGSRC) ;       break;    default:        die ("Unsupported watermark picture file type");        exit;   }        Imagedestroy ($dst _img);   imagedestroy ($SRCIM);}

Parameter description:

$IMGSRC: Target image, with relative directory address,

$MARKIMG: Watermark picture, with relative directory address, support PNG and GIF two formats, such as watermark picture in the execution file mark directory, can be written as: Mark/mark.gif

$markText: Watermark text added to a picture

$TextColor: Font color for watermark text

$markPos: Image watermark Add location, value range: 0~9

0: Random position, randomly pick a position between 1~8

1: Top left 2: Top Center 3: Top right 4: Left center

5: Picture Center 6: Right Center 7: Bottom left 8: Bottom Center 9: Bottom Right

$fontType: Specific font library with relative directory address

$markType: How to add a watermark to a picture, IMG represents a picture, and text means to add a watermark in text

Code Comment:

Line 4th to 6th: Get the width and height of the target picture

Line 8th to 22nd: Call different functions according to the picture type, get the action image identifier

getimagesize function Knowledge Point: getimagesize does not need to install GD degree can be used, its return value array has four elements. The index value 0 is the height of the picture. The index value 1 is the width of the picture. The index value 2 is the file format of the picture, with a value of 1 in GIF format, 2 in jpeg/jpg format, and 3 in PNG format. The index value 3 is the height and width of the picture string, Height=xxx width=yyy. The returned picture width and height units are pixels (pixel)

Line 24th to 58th: When the image is selected to add a watermark to the target image, get the width and height of the watermark picture, usually the site's logo. If the target image is smaller than the width or height of the watermark image or the watermark image does not exist, jump out of this function.

Return statement knowledge Point: Direct return indicates that nothing is returned and ends the function directly. It can also be interpreted as returning NULL.

Line 60th to 77th: When you select text to add a watermark to the target picture, first set the size of the watermark text, the default I set to 16PX, you can adjust the font size according to your own needs. If the font file does not exist, jump out of the function and finally get the virtual length width of this formatted text via the Imagettfbbox function.

Imagettfbbox function Knowledge Point: This function returns an array of 8 cells representing the four corners of the text box, the index value meaning: 0 for the lower left corner x position, 1 for sitting down angle y position, 2 for the lower right corner x position, 3 for the lower right corner, 4 for the upper right x position, and 5 for the upper right corner y position , 6 represents the upper-left X position, and 7 represents the upper-left corner Y position. This function also requires the support of the GD library and the FreeType library

The Max function returns the value that has the largest number in the parameter.

Line 79th to 125th: According to the image Watermark location to calculate the specific coordinate values, you can refine the location of the watermark according to the effect.

Line 127th to 129th: Create a new picture with the same size as the target picture.

Note: Since the Imagecreatetruecolor function range is a black picture, if your target image is transparent, the resulting new diagram will not be a transparent color.

Line 131th to 162th: According to the image or text, the final generation of a watermark added image.

Invocation Description:

It can be called as a function call, but you can also encapsulate it in a class, or you can further subdivide the function as needed. Of course, you do not have any problems with this now, I have tested, please feel free to use.

Other Notes:

Because the Imagettftext and Imagettfbbox functions require the support of the GD library and the FreeType library, if your operating environment does not support the GD library and the FreeType library, the text method cannot be implemented. You can use the Imagestring function to add a text watermark to a picture, while setting the $logow and $logoh values under the text mode.

The Imagejpeg function can also set the image quality of the composition.

Setwater ($to _img_name, $sy _path $v. png ', ', ', ', 9, ', ' img ');

Excerpt from the Script house

PHP Implementation Watermark effect (text, picture)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.