PHP implementation of a picture to add a watermark effect _php instance

Source: Internet
Author: User
Tags getcolor image identifier imagecopy imagejpeg transparent color rtrim strcmp unsupported
PHP implementation of a picture to add watermark effect

<?php/** * Function: Add watermark effect to a picture * $i image to add watermark * $t Watermark Text * $size Text size * $pos The location of the watermark * $color the color of the text * $flag is a Boolean value, mainly used to distinguish whether the original image watermark * $type if $flag equals false the new map watermark new file name _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;      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);    Case ' black ': $cc =imagecolorallocatealpha ($i, 0,0,0, $a);    Case ' red ': $cc =imagecolorallocatealpha ($i, 255,0,0, $a);    Case ' green ': $cc =imagecolorallocatealpha ($i, 0,255,0, $a);    Case ' Blue ': $cc =imagecolorallocatealpha ($i, 0,0,255, $a);    Case ' orange ': $cc =imagecolorallocatealpha ($i, 0xff,0x66,0x33, $a);    Case ' yellow ': $cc =imagecolorallocatealpha ($i, 255,255,0, $a);    Case ' rand ': $CC =imagecolorallocatealpha ($i, Mt_rand (0,255), Mt_rand (0,255), Mt_rand (0,255), $a);      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));}

Let's take a look at a support to add a watermark to a picture in two ways: Picture and text. 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 image file type");   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 image file type");     Exit    } $logow = $markImg _w;  $logoh = $MARKIMG _h;    } if (!strcmp ($markType, "text")) {$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 image 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.

  • 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.