Php: adding a watermark to an image _ php example

Source: Internet
Author: User
Tags image identifier imagecopy imagejpeg php example rtrim unsupported
This article summarizes two php functions that can be used to add watermarks to images. The first one is easier to understand and the second one is more powerful and encapsulated, if you have any need, you can refer to php to add a watermark to an image.

<? Php/*** features: add a watermark effect to an image * $ I image to add a watermark effect * $ t watermark text * $ size text size * $ pos watermark position * $ color text color * $ flag Yes boolean value, it is mainly used to identify whether the source image is watermark * $ type. If $ flag is equal to false, the new image is added with the watermark. The new file name is the original name _txt.jpg */function txt ($ I, $ t = 'copyright right ', $ 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, 255, $ ); 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]), $ ); break;} return $ cc;}/*** function: returns the extension */function ext ($ f) {$ exts = explode ('. ', $ f); return end ($ exts);}/*** function: return the file name, excluding the extension */function name ($ f) {$ s = explode ('/', $ f); $ fn = end ($ s); return rtrim ($ fn ,'. '. ext ($ f ));}

Let's take a look at adding watermarks to images and text. Images can be in GIF, PNG, or JPG formats. Watermarks can be in PNG or GIF formats.

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 types"); 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 is not supported"); 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 a relative directory address,
$ MarkImg: a watermark image with a relative directory address. It supports PNG and GIF formats. For example, if a watermark image is under the mark directory of an execution file, it can be written as: mark/mark.gif.
$ MarkText: watermark text added to an image
$ TextColor: The font color of the watermark text
$ MarkPos: Position of the image watermark. value range: 0 ~ 9
0: random position, ranging from 1 ~ Select a random location between 8
1: Top center left 2: Top center 3: Top center right 4: left center
5: Image Center 6: center on the right 7: center on the bottom 8: center on the bottom 9: center on the right
$ FontType: The specific library with the relative directory address
$ MarkType: the watermark method for an image. img indicates adding a watermark as an image, and text indicates adding a watermark as a text.

Code comment:

4th ~ Row 6: Obtain the width and height of the target image.
8th ~ Row 22: Call different functions based on the image type to obtain the operation image identifier.

Knowledge Point of the GetImageSize function: GetImageSize can be used without the GD degree installed. The returned value array has four elements. The index value 0 indicates the Image Height. Index value 1 indicates the image width. The index value 2 is the image file format. The value 1 is GIF, 2 is JPEG/JPG, and 3 is PNG. The index value 3 is the string of the image height and width, and the height is xxx width = yyy. The returned image width and height are measured in pixels)

24th ~ Row 58: When you select the image method to watermark the target image, you can obtain the width and height of the watermark image. Generally, it is the website logo. If the target image is smaller than the width or height of the watermark image or the watermark image does not exist, this function is displayed.

Return Statement knowledge point: direct return indicates that nothing is returned and this function is directly ended. It can also be interpreted as returning NULL.

60th ~ Row 77: when selecting the text method to flat the target image with watermarks, first set the watermark text size. The default value is 16px. You can adjust the font size as needed. If the font file does not exist, jump out of the function and use the imagettfbbox function to obtain the virtual length and width of the text in the specified format.

Imagettfbbox function knowledge point: this function returns an array containing eight units to represent the four corners of the text box. The index value meaning: 0 represents the position X in the lower left corner, and 1 represents the position Y in the lower right corner, 2 represents the position X in the lower right corner, 3 represents the position Y in the lower right corner, 4 represents the position X in the upper right corner, 5 represents the position Y in the upper right corner, 6 represents the position X in the upper left corner, and 7 represents the position Y in the upper left corner. This function must be supported by both the GD library and the FreeType library.
The max function returns the maximum value of a parameter.

79th ~ Row 125: calculates the coordinate value based on the watermark position. You can refine the watermark position based on the effect.

127th ~ Row 3: create an image with the same size as the target image.

Note: Because the range of the imagecreatetruecolor function is a black image, if your target image is transparent, the new image will not be transparent.

131st ~ Row 3: the watermark is generated based on the image or text format.

Call description:

You can call the function as a function call. Of course, you can encapsulate the function as a class, or you can further segment the module as needed. Of course, you can use it now without any problems. I have tested it. Please feel free to use it.

Other Instructions:

The imagettftext and imagettfbbox functions require the support of the GD library and FreeType library. If your runtime environment does not support the GD library and FreeType library, the text mode cannot be implemented, you can use the imagestring function to add a text watermark to the image and set the $ logow and $ logoh values in the text mode.

The imagejpeg function can also set the quality of the merged image.

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.