Php code for adding a Chinese watermark to an image

Source: Internet
Author: User
Tags imagecopy
Php code for adding a Chinese watermark to an image

  1. Header ("Content-type: image/png");/* notify the browser to output the image */
  2. $ Im = imagecreate (400,300);/* define the image size */
  3. $ Gray = ImageColorAllocate ($ im, 235,235,235 );
  4. $ Pink = ImageColorAllocate ($ im, 255,128,255 );
  5. $ Fontfile = "simkai. ttf ";
  6. /* $ Fontfile font path, depending on the operating system, can be simhei. ttf (), SIMKAI. TTF (entity body), SIMFANG. TTF (Imitation Song), SIMSUN. chinese fonts supported by GD, such as TTC (& */
  7. $ Str = iconv ('gb2312', 'utf-8', 'Chinese watermark');/* convert the GB2312 character set to the character set of the UTF-8 */
  8. ImageTTFText ($ im, 30, 0,100,200, $ pink, $ fontfile, $ str );
  9. /* Add a Chinese watermark */
  10. Imagepng ($ im );
  11. ImageDestroy ($ im );
  12. ?>

Example 2:

  1. //-----------------------//
  2. // Function: add text to the image
  3. // Parameter: $ img image file name
  4. // $ New_img saves another image file name. if it is null, it means no other image is saved.
  5. // $ Text string content
  6. // Text_size string size
  7. // Text_angle font string output angle
  8. // Output x coordinate of text_x string
  9. // Output y coordinate from text_y string
  10. // $ Text_font-shaped file name
  11. // $ R, $ g, $ B string color RGB value
  12. //-------------------------//
  13. Function img_text ($ img, $ new_img, $ text, $ text_size, $ text_angle, $ text_x, $ text_y, $ text_font, $ r, $ g, $ B ){
  14. $ Text = iconv ("gb2312", "UTF-8", $ text );
  15. Header ("Content-type: image/gif ");
  16. $ Im = @ imagecreatefromstring (file_get_contents ($ img) or die ("Opening the image failed! ");
  17. $ Color = ImageColorAllocate ($ im, $ r, $ g, $ B );
  18. // ImageTTFText (int im, int size, int angle, int x, int y, int col, string fontfile, string text ):
  19. // This function writes TTF (TrueType Fonts) text to an image.
  20. // Parameter: the size is the font size;
  21. // Angle is the font angle, which is calculated clockwise. 0 degrees is horizontal (from left to right), and 90 degrees is the bottom-to-top text;
  22. // The x and y parameters are the coordinate values of the text (the origin is the upper left corner );
  23. // Col indicates the color of the word;
  24. // Fontfile is the font file name;
  25. // Text is the string content.
  26. ImageTTFText ($ im, $ text_size, $ text_angle, $ text_x, $ text_y, $ color, $ text_font, $ text );
  27. If ($ new_img = ""):
  28. ImageGif ($ im); // do not save the image, only show
  29. Else:
  30. ImageGif ($ im, $ new_img); // save the image but it is not displayed
  31. Endif;
  32. ImageDestroy ($ im); // ends the image and releases the memory space.
  33. }
  34. ?>

Example 3:

  1. /*
  2. * Function: PHP image watermark (watermarks support images or text)
  3. * Parameters:
  4. * $ GroundImage: specifies the background image to be Watermark. Currently, only GIF, JPG, and PNG formats are supported;
  5. * $ WaterPos watermark position, which has 10 statuses. 0 indicates a random position;
  6. * 1 is the top left, 2 is the top center, and 3 is the top right;
  7. * 4: center left, 5: center, and 6: center right;
  8. * 7 indicates that the bottom is left, 8 indicates that the bottom is center, and 9 indicates that the bottom is right;
  9. * $ WaterImage: specifies the image Watermark. Currently, only the GIF, JPG, and PNG formats are supported;
  10. * $ WaterText text watermark: uses text as a watermark. it supports ASCII codes and does not support Chinese characters;
  11. * $ TextFont text size. The value is 1, 2, 3, 4, or 5. the default value is 5;
  12. * $ TextColor text color. The value is a hexadecimal color value. The default value is # FF0000 (red );
  13. *
  14. * Note: Support GD 2.0, Support FreeType, GIF Read, GIF Create, JPG, and PNG
  15. * $ WaterImage and $ waterText should not be used at the same time. select one of them and use $ waterImage first.
  16. * When $ waterImage is valid, $ waterString, $ stringFont, and $ stringColor are invalid.
  17. * The name of the watermark image is the same as that of $ groundImage.
  18. * Author: longware @ 2004-11-3 14:15:13
  19. */
  20. Function imageWaterMark ($ groundImage, $ waterPos = 0, $ waterImage = "", $ waterText = "", $ textFont = 5, $ textColor = "# FF0000 ″)
  21. {
  22. $ IsWaterImage = FALSE;
  23. $ FormatMsg = "this file format is not supported Currently. use image processing software to convert images to GIF, JPG, and PNG formats .";
  24. // Read the watermark file
  25. If (! Emptyempty ($ waterImage) & file_exists ($ waterImage ))
  26. {
  27. $ IsWaterImage = TRUE;
  28. $ Water_info = getimagesize ($ waterImage );
  29. $ Water_w = $ water_info [0]; // Obtain the watermark image width.
  30. $ Water_h = $ water_info [1]; // Get the watermark image height
  31. Switch ($ water_info [2]) // Obtain the watermark image format
  32. {
  33. Case 1: $ water_im = imagecreatefromgif ($ waterImage); break;
  34. Case 2: $ water_im = imagecreatefromjpeg ($ waterImage); break;
  35. Case 3: $ water_im = imagecreatefrompng ($ waterImage); break;
  36. Default: die ($ formatMsg );
  37. }
  38. }
  39. // Read the background image
  40. If (! Emptyempty ($ groundImage) & file_exists ($ groundImage ))
  41. {
  42. $ Ground_info = getimagesize ($ groundImage );
  43. $ Ground_w = $ ground_info [0]; // Obtain the width of the background image.
  44. $ Ground_h = $ ground_info [1]; // get the height of the background image
  45. Switch ($ ground_info [2]) // Obtain the background image format
  46. {
  47. Case 1: $ ground_im = imagecreatefromgif ($ groundImage); break;
  48. Case 2: $ ground_im = imagecreatefromjpeg ($ groundImage); break;
  49. Case 3: $ ground_im = imagecreatefrompng ($ groundImage); break;
  50. Default: die ($ formatMsg );
  51. }
  52. }
  53. Else
  54. {
  55. Die ("the image to be watermarked does not exist !");
  56. }
  57. // Watermark Position
  58. If ($ isWaterImage) // image watermark
  59. {
  60. $ W = $ water_w;
  61. $ H = $ water_h;
  62. $ Label = "image ";
  63. }
  64. Else // text watermark
  65. {
  66. $ Temp = imagettfbbox (ceil ($ textFont * 5), 0, "./cour. ttf", $ waterText); // get the text range using the TrueType font
  67. $ W = $ temp [2]-$ temp [6];
  68. $ H = $ temp [3]-$ temp [7];
  69. Unset ($ temp );
  70. $ Label = "text area ";
  71. }
  72. If ($ ground_w <$ w) | ($ ground_h <$ h ))
  73. {
  74. Echo "the length or width of the image to be watermarked is smaller than that of the watermark". $ label. ", the watermark cannot be generated !";
  75. Return;
  76. }
  77. Switch ($ waterPos)
  78. {
  79. Case 0: // random
  80. $ PosX = rand (0, ($ ground_w-$ w ));
  81. $ PosY = rand (0, ($ ground_h-$ h ));
  82. Break;
  83. Case 1: // 1 is the top left
  84. $ PosX = 0;
  85. $ PosY = 0;
  86. Break;
  87. Case 2: // 2 center the top
  88. $ PosX = ($ ground_w-$ w)/2;
  89. $ PosY = 0;
  90. Break;
  91. Case 3: // 3: top right
  92. $ PosX = $ ground_w-$ w;
  93. $ PosY = 0;
  94. Break;
  95. Case 4: // 4 is left in the middle
  96. $ PosX = 0;
  97. $ PosY = ($ ground_h-$ h)/2;
  98. Break;
  99. Case 5: // 5 center in the middle
  100. $ PosX = ($ ground_w-$ w)/2;
  101. $ PosY = ($ ground_h-$ h)/2;
  102. Break;
  103. Case 6: // 6 is the center and right
  104. $ PosX = $ ground_w-$ w;
  105. $ PosY = ($ ground_h-$ h)/2;
  106. Break;
  107. Case 7: // 7 is left at the bottom
  108. $ PosX = 0;
  109. $ PosY = $ ground_h-$ h;
  110. Break;
  111. Case 8: // 8 is centered at the bottom
  112. $ PosX = ($ ground_w-$ w)/2;
  113. $ PosY = $ ground_h-$ h;
  114. Break;
  115. Case 9: // 9: right
  116. $ PosX = $ ground_w-$ w;
  117. $ PosY = $ ground_h-$ h;
  118. Break;
  119. Default: // random
  120. $ PosX = rand (0, ($ ground_w-$ w ));
  121. $ PosY = rand (0, ($ ground_h-$ h ));
  122. Break;
  123. }
  124. // Set the mixed color mode of the image
  125. Imagealphablending ($ ground_im, true );
  126. If ($ isWaterImage) // image watermark
  127. {
  128. Imagecopy ($ ground_im, $ water_im, $ posX, $ posY, 0, 0, $ water_w, $ water_h); // Copy the watermark to the target file
  129. }
  130. Else // text watermark
  131. {
  132. If (! Emptyempty ($ textColor) & (strlen ($ textColor) = 7 ))
  133. {
  134. $ R = hexdec (substr ($ textColor, 1, 2 ));
  135. $ G = hexdec (substr ($ textColor, 3, 2 ));
  136. $ B = hexdec (substr ($ textColor, 5 ));
  137. }
  138. Else
  139. {
  140. Die ("incorrect watermark text color format !");
  141. }
  142. Imagestring ($ ground_im, $ textFont, $ posX, $ posY, $ waterText, imagecolorallocate ($ ground_im, $ R, $ G, $ B ));
  143. }
  144. // The image after the watermark is generated
  145. @ Unlink ($ groundImage );
  146. Switch ($ ground_info [2]) // Obtain the background image format
  147. {
  148. Case 1: imagegif ($ ground_im, $ groundImage); break;
  149. Case 2: imagejpeg ($ ground_im, $ groundImage); break;
  150. Case 3: imagepng ($ ground_im, $ groundImage); break;
  151. Default: die ($ errorMsg );
  152. }
  153. // Release the memory
  154. If (isset ($ water_info) unset ($ water_info );
  155. If (isset ($ water_im) imagedestroy ($ water_im );
  156. Unset ($ ground_info );
  157. Imagedestroy ($ ground_im );
  158. }
  159. //-----------------------------
  160. $ Id = $ _ REQUEST ['id'];
  161. $ Num = count ($ _ FILES ['userfile'] ['name']);
  162. Print_r ($ _ FILES ['userfile']);
  163. Print_r ($ _ FILES ['userfile'] ['name']);
  164. Echo $ num;
  165. Echo"
    ";
  166. If (isset ($ id )){
  167. For ($ I = 0; $ I <$ id; $ I ++ ){
  168. If (isset ($ _ FILES )&&! Emptyempty ($ _ FILES ['userfile']) & $ _ FILES ['userfile'] ['size']> 0)
  169. {
  170. $ Uploadfile = "./". time (). "_". $ _ FILES ['userfile'] [name] [$ I];
  171. Echo"
    ";
  172. Echo $ uploadfile;
  173. If (copy ($ _ FILES ['userfile'] ['tmp _ name'] [$ I], $ uploadfile ))
  174. {
  175. Echo "OK
    ";
  176. // Text watermark
  177. // ImageWaterMark ($ uploadfile, 5, "", "HTTP: // www.lvye.info", 5, "# cccccc");
  178. // Image watermark
  179. Watermark waterimage##logo_ok1.gif "; // watermark image path
  180. ImageWaterMark ($ uploadfile, 9, $ waterImage );
  181. Echo "";
  182. }
  183. Else
  184. {
  185. Echo "Fail
    ";
  186. }
  187. }
  188. }
  189. }
  190. ?>

Example 4: Add a Chinese Watermark:

  1. /*--------------

  2. ** Description: This is a custom class used to add a bottom watermark (not occupying the image display area) to a specified image. you need to create an object to call this class.
  3. ** Note: 1. the gd Library is required and iconv is required (php5 already contains and does not need to be loaded)
  4. 2. only applicable to three types of images: jpg, jpeg, gif, and png. do not process other types of images.
  5. 3. Note that the attribute of the image directory must be writable.
  6. 4. call example:
  7. $ ObjImg = new MyWaterDownChinese ();
  8. $ ObjImg-> Path = "images /";
  9. $ ObjImg-> FileName = "1.jpg ";
  10. $ ObjImg-> Text = "HAHAKONGJIAN [url] HTTP: // HI. BAIDU. COM/LYSONCN [/url]";
  11. $ ObjImg-> Font = "./font/simhei. ttf ";
  12. $ ObjImg-> Run ();
  13. ** Member functions:
  14. -------------*/
  15. Class MyWaterDownChinese {
  16. Var $ Path = "./"; // relative Path of the image directory to the page that calls this class
  17. Var $ FileName = ""; // The name of the image, for example, JPG"
  18. Var $ Text = ""; // The watermark Text to be added to the image. Chinese characters are supported.
  19. Var $ TextColor = "# ffffff"; // text color. the font color must be black when the GIF image is used.
  20. Var $ TextBgColor = "#000000"; // The color of the text background bar
  21. Var $ Font = "c: // windows // fonts // simhei. ttf"; // Directory for storing fonts, relative path
  22. Var $ OverFlag = true; // specifies whether to overwrite the source image. if the source image is not overwritten by default, the system automatically adds "_ water_down" after the source image file name, for example, “1.jpg "=>" 1_water_down.jpg"
  23. Var $ BaseWidth = 200; // The watermark text is added only when the image width is greater than or equal to 200.
  24. //----------------
  25. // Function: constructor of the class (php5.0 or above)
  26. // Parameter: None
  27. // Return: None
  28. Function _ construct (){;}
  29. //---------------
  30. // Function: class destructor (php5.0 or above)
  31. // Parameter: None
  32. // Return: None
  33. Function _ destruct (){;}
  34. //-------------

  35. // Function: run the object function and add a watermark to the image.

  36. // Parameter: None
  37. // Return: None
  38. Function Run ()
  39. {
  40. If ($ this-> FileName = "" | $ this-> Text = "")
  41. Return;
  42. // Check whether the GD Library is installed
  43. If (false = function_exists ("gd_info "))
  44. {
  45. Echo "the GD library is not installed in the system, and watermarks cannot be added to images .";
  46. Return;
  47. }
  48. // Set the input and output image pathnames
  49. $ Arr_in_name = explode (".", $ this-> FileName );
  50. //
  51. $ InImg = $ this-> Path. $ this-> FileName;
  52. $ OutImg = $ inImg;
  53. $ TmpImg = $ this-> Path. $ arr_in_name [0]. "_ tmp.". $ arr_in_name [1]; // temporarily processed image, very important
  54. If (! $ This-> OverFlag)
  55. $ OutImg = $ this-> Path. $ arr_in_name [0]. "_ water_down.". $ arr_in_name [1];
  56. // Check whether the image exists
  57. If (! File_exists ($ inImg ))
  58. Return;
  59. // Obtain Image attributes
  60. $ GroundImageType = @ getimagesize ($ inImg );
  61. $ ImgWidth = $ groundImageType [0];
  62. $ ImgHeight = $ groundImageType [1];
  63. $ ImgType = $ groundImageType [2];
  64. If ($ imgWidth <$ this-> BaseWidth) // smaller than the basic width, not processed
  65. Return;
  66. // When the image is not jpg/jpeg/gif/png, it is not processed
  67. Switch ($ imgType)
  68. {
  69. Case 1:
  70. $ Image = imagecreatefromgif ($ inImg );
  71. $ This-> TextBgColor = "# ffffff"; // The GIF image font can only be black, so the background color is white.
  72. Break;
  73. Case 2:
  74. $ Image = imagecreatefromjpeg ($ inImg );
  75. Break;
  76. Case 3:
  77. $ Image = imagecreatefrompng ($ inImg );
  78. Break;
  79. Default:
  80. Return;
  81. Break;
  82. }
  83. // Create a color
  84. $ Color = @ imagecolorallocate ($ image, hexdec (substr ($ this-> TextColor, 1, 2), hexdec (substr ($ this-> TextColor, 3, 2 )), hexdec (substr ($ this-> TextColor, 5, 2); // text color
  85. // Generate an empty image. its height increases the watermark height at the bottom.
  86. $ NewHeight = $ imgHeight + 20;
  87. $ ObjTmpImg = @ imagecreatetruecolor ($ imgWidth, $ newHeight );
  88. $ ColorBg = @ imagecolorallocate ($ objTmpImg, hexdec (substr ($ this-> TextBgColor, 1, 2), hexdec (substr ($ this-> TextBgColor, 3, 2 )), hexdec (substr ($ this-> TextBgColor, 5, 2); // background color
  89. // Fill in the background color of the image
  90. @ Imagefill ($ objTmpImg, 0, 0, $ colorBg );
  91. // Copy the source image to the temporary Image
  92. @ Imagecopy ($ objTmpImg, $ image, 0, 0, 0, $ imgWidth, $ imgHeight );
  93. // Create the watermark text object to be written
  94. $ ObjText = $ this-> createText ($ this-> Text );
  95. // Calculate the position of the watermark text to be written
  96. $ X = 5;
  97. $ Y = $ newHeight-5;
  98. // Write a text watermark
  99. @ Imagettftext ($ objTmpImg, 10, 0, $ x, $ y, $ color, $ this-> Font, $ objText );
  100. // Generate a new image and a temporary Image
  101. Switch ($ imgType)
  102. {
  103. Case 1:
  104. Imagegif ($ objTmpImg, $ tmpImg );
  105. Break;
  106. Case 2:
  107. Imagejpeg ($ objTmpImg, $ tmpImg );
  108. Break;
  109. Case 3:
  110. Imagepng ($ objTmpImg, $ tmpImg );
  111. Break;
  112. Default:
  113. Return;
  114. Break;
  115. }
  116. // Release resources
  117. @ Imagedestroy ($ objTmpImg );
  118. @ Imagedestroy ($ image );
  119. // Rename the file
  120. If ($ this-> OverFlag)
  121. {
  122. // Overwrite the source image
  123. @ Unlink ($ inImg );
  124. @ Rename ($ tmpImg, $ outImg );
  125. }
  126. Else
  127. {
  128. // Do not overwrite the source image
  129. @ Rename ($ tmpImg, $ outImg );
  130. }
  131. }
  132. //-------
  133. // Function: Create a watermark text object
  134. // Parameter: None
  135. // Return: the created watermark text object.
  136. Function createText ($ instring)
  137. {
  138. $ Outstring = "";
  139. $ Max = strlen ($ instring );
  140. For ($ I = 0; $ I <$ max; $ I ++)
  141. {
  142. $ H = ord ($ instring [$ I]);
  143. If ($ h >=160 & $ I <$ MAX-1)
  144. {
  145. $ Outstring. = "&#". base_convert (bin2hex (iconv ("gb2312", "UCS-2", substr ($ instring, $ I, 2), 16, 10 ). ";";
  146. $ I ++;
  147. }
  148. Else
  149. {
  150. $ Outstring. = $ instring [$ I];
  151. }
  152. }
  153. Return $ outstring;
  154. }
  155. } // Class
  156. ?>

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.