Php image and Chinese watermark implementation code sharing

Source: Internet
Author: User
Tags imagecopy imagejpeg
In php, adding watermarks to Chinese characters requires some simple processing. one is to convert characters into gbk, and the other is to load Chinese fonts, with these two conditions, adding a Chinese watermark to the image is simple.

Example 1
Copy codeThe code is as follows:
Header ("Content-type: image/png");/* notify the browser to output the image */
$ Im = imagecreate (400,300);/* define the image size */
$ Gray = ImageColorAllocate ($ im, 235,235,235 );
$ Pink = ImageColorAllocate ($ im, 255,128,255 );
$ Fontfile = "simkai. ttf ";
/* $ 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 (& */
$ Str = iconv ('gb2312', 'utf-8', 'Chinese watermark');/* convert the GB2312 character set to the character set of the UTF-8 */
ImageTTFText ($ im, 30, 0,100,200, $ pink, $ fontfile, $ str );
/* Add a Chinese watermark */
Imagepng ($ im );
ImageDestroy ($ im );
?>

Example 2
Copy codeThe code is as follows:
//************************************** **//
// Function: add text to the image
// Parameter: $ img image file name
// $ New_img saves another image file name. if it is null, it means no other image is saved.
// $ Text string content
// Text_size string size
// Text_angle font string output angle
// Output x coordinate of text_x string
// Output y coordinate from text_y string
// $ Text_font-shaped file name
// $ R, $ g, $ B string color RGB value
//************************************** **//
Function img_text ($ img, $ new_img, $ text, $ text_size, $ text_angle, $ text_x, $ text_y, $ text_font, $ r, $ g, $ B ){
$ Text = iconv ("gb2312", "UTF-8", $ text );
Header ("Content-type: image/gif ");
$ Im = @ imagecreatefromstring (file_get_contents ($ img) or die ("Opening the image failed! ");
$ Color = ImageColorAllocate ($ im, $ r, $ g, $ B );
// ImageTTFText (int im, int size, int angle, int x, int y, int col, string fontfile, string text ):
// This function writes TTF (TrueType Fonts) text to an image.
// Parameter: the size is the font size;
// 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;
// The x and y parameters are the coordinate values of the text (the origin is the upper left corner );
// Col indicates the color of the word;
// Fontfile is the font file name;
// Text is the string content.
ImageTTFText ($ im, $ text_size, $ text_angle, $ text_x, $ text_y, $ color, $ text_font, $ text );
If ($ new_img = ""):
ImageGif ($ im); // do not save the image, only show
Else:
ImageGif ($ im, $ new_img); // save the image but it is not displayed
Endif;
ImageDestroy ($ im); // ends the image and releases the memory space.
}
?>

Example 3
Copy codeThe code is as follows:
/*
* Function: PHP image watermark (watermarks support images or text)
* Parameters:
* $ GroundImage: specifies the background image to be Watermark. Currently, only GIF, JPG, and PNG formats are supported;
* $ WaterPos watermark position, which has 10 statuses. 0 indicates a random position;
* 1 is the top left, 2 is the top center, and 3 is the top right;
* 4: center left, 5: center, and 6: center right;
* 7 indicates that the bottom is left, 8 indicates that the bottom is center, and 9 indicates that the bottom is right;
* $ WaterImage: specifies the image Watermark. Currently, only the GIF, JPG, and PNG formats are supported;
* $ WaterText text watermark: uses text as a watermark. it supports ASCII codes and does not support Chinese characters;
* $ TextFont text size. The value is 1, 2, 3, 4, or 5. the default value is 5;
* $ TextColor text color. The value is a hexadecimal color value. The default value is # FF0000 (red );
*
* Note: Support GD 2.0, Support FreeType, GIF Read, GIF Create, JPG, and PNG
* $ WaterImage and $ waterText should not be used at the same time. select one of them and use $ waterImage first.
* When $ waterImage is valid, $ waterString, $ stringFont, and $ stringColor are invalid.
* The name of the watermark image is the same as that of $ groundImage.
* Author: longware @ 2004-11-3 14:15:13
*/
Function imageWaterMark ($ groundImage, $ waterPos = 0, $ waterImage = "", $ waterText = "", $ textFont = 5, $ textColor = "# FF0000 ″)
{
$ IsWaterImage = FALSE;
$ FormatMsg = "this file format is not supported Currently. use image processing software to convert images to GIF, JPG, and PNG formats .";
// Read the watermark file
If (! Emptyempty ($ waterImage) & file_exists ($ waterImage ))
{
$ IsWaterImage = TRUE;
$ Water_info = getimagesize ($ waterImage );
$ Water_w = $ water_info [0]; // Obtain the watermark image width.
$ Water_h = $ water_info [1]; // Get the watermark image height
Switch ($ water_info [2]) // Obtain the watermark image format
{
Case 1: $ water_im = imagecreatefromgif ($ waterImage); break;
Case 2: $ water_im = imagecreatefromjpeg ($ waterImage); break;
Case 3: $ water_im = imagecreatefrompng ($ waterImage); break;
Default: die ($ formatMsg );
}
}
// Read the background image
If (! Emptyempty ($ groundImage) & file_exists ($ groundImage ))
{
$ Ground_info = getimagesize ($ groundImage );
$ Ground_w = $ ground_info [0]; // Obtain the width of the background image.
$ Ground_h = $ ground_info [1]; // get the height of the background image
Switch ($ ground_info [2]) // Obtain the background image format
{
Case 1: $ ground_im = imagecreatefromgif ($ groundImage); break;
Case 2: $ ground_im = imagecreatefromjpeg ($ groundImage); break;
Case 3: $ ground_im = imagecreatefrompng ($ groundImage); break;
Default: die ($ formatMsg );
}
}
Else
{
Die ("the image to be watermarked does not exist !");
}
// Watermark Position
If ($ isWaterImage) // image watermark
{
$ W = $ water_w;
$ H = $ water_h;
$ Label = "image ";
}
Else // text watermark
{
$ Temp = imagettfbbox (ceil ($ textFont * 5), 0, "./cour. ttf", $ waterText); // get the text range using the TrueType font
$ W = $ temp [2]-$ temp [6];
$ H = $ temp [3]-$ temp [7];
Unset ($ temp );
$ Label = "text area ";
}
If ($ ground_w <$ w) | ($ ground_h <$ h ))
{
Echo "the length or width of the image to be watermarked is smaller than that of the watermark". $ label. ", the watermark cannot be generated !";
Return;
}
Switch ($ waterPos)
{
Case 0: // random
$ PosX = rand (0, ($ ground_w-$ w ));
$ PosY = rand (0, ($ ground_h-$ h ));
Break;
Case 1: // 1 is the top left
$ PosX = 0;
$ PosY = 0;
Break;
Case 2: // 2 center the top
$ PosX = ($ ground_w-$ w)/2;
$ PosY = 0;
Break;
Case 3: // 3: top right
$ PosX = $ ground_w-$ w;
$ PosY = 0;
Break;
Case 4: // 4 is left in the middle
$ PosX = 0;
$ PosY = ($ ground_h-$ h)/2;
Break;
Case 5: // 5 center in the middle
$ PosX = ($ ground_w-$ w)/2;
$ PosY = ($ ground_h-$ h)/2;
Break;
Case 6: // 6 is the center and right
$ PosX = $ ground_w-$ w;
$ PosY = ($ ground_h-$ h)/2;
Break;
Case 7: // 7 is left at the bottom
$ PosX = 0;
$ PosY = $ ground_h-$ h;
Break;
Case 8: // 8 is centered at the bottom
$ PosX = ($ ground_w-$ w)/2;
$ PosY = $ ground_h-$ h;
Break;
Case 9: // 9: right
$ PosX = $ ground_w-$ w;
$ PosY = $ ground_h-$ h;
Break;
Default: // random
$ PosX = rand (0, ($ ground_w-$ w ));
$ PosY = rand (0, ($ ground_h-$ h ));
Break;
}
// Set the mixed color mode of the image
Imagealphablending ($ ground_im, true );
If ($ isWaterImage) // image watermark
{
Imagecopy ($ ground_im, $ water_im, $ posX, $ posY, 0, 0, $ water_w, $ water_h); // Copy the watermark to the target file
}
Else // text watermark
{
If (! Emptyempty ($ textColor) & (strlen ($ textColor) = 7 ))
{
$ R = hexdec (substr ($ textColor, 1, 2 ));
$ G = hexdec (substr ($ textColor, 3, 2 ));
$ B = hexdec (substr ($ textColor, 5 ));
}
Else
{
Die ("incorrect watermark text color format !");
}
Imagestring ($ ground_im, $ textFont, $ posX, $ posY, $ waterText, imagecolorallocate ($ ground_im, $ R, $ G, $ B ));
}
// The image after the watermark is generated
@ Unlink ($ groundImage );
Switch ($ ground_info [2]) // Obtain the background image format
{
Case 1: imagegif ($ ground_im, $ groundImage); break;
Case 2: imagejpeg ($ ground_im, $ groundImage); break;
Case 3: imagepng ($ ground_im, $ groundImage); break;
Default: die ($ errorMsg );
}
// Release the memory
If (isset ($ water_info) unset ($ water_info );
If (isset ($ water_im) imagedestroy ($ water_im );
Unset ($ ground_info );
Imagedestroy ($ ground_im );
}
//-----------------------------
$ Id = $ _ REQUEST ['id'];
$ Num = count ($ _ FILES ['userfile'] ['name']);
Print_r ($ _ FILES ['userfile']);
Print_r ($ _ FILES ['userfile'] ['name']);
Echo $ num;
Echo"
";
If (isset ($ id )){
For ($ I = 0; $ I <$ id; $ I ++ ){
If (isset ($ _ FILES )&&! Emptyempty ($ _ FILES ['userfile']) & $ _ FILES ['userfile'] ['size']> 0)
{
$ Uploadfile = "./". time (). "_". $ _ FILES ['userfile'] [name] [$ I];
Echo"
";
Echo $ uploadfile;
If (copy ($ _ FILES ['userfile'] ['tmp _ name'] [$ I], $ uploadfile ))
{
Echo "OK
";
// Text watermark
// ImageWaterMark ($ uploadfile, 5, "", "HTTP: // www.lvye.info", 5, "# cccccc");
// Image watermark
Watermark waterimage##logo_ok1.gif "; // watermark image path
ImageWaterMark ($ uploadfile, 9, $ waterImage );
Echo "";
}
Else
{
Echo "Fail
";
}
}
}
}
?>


Code 4
Copy codeThe code is as follows:
Add Chinese watermark
/*-------------------------------------------------------------
** 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.
** Creation: 2007-10-09
** Updated: 2007-10-09
** Note: 1. the gd Library is required and iconv is required (php5 already contains and does not need to be loaded)
2. only applicable to three types of images: jpg, jpeg, gif, and png. do not process other types of images.
3. Note that the attribute of the image directory must be writable.
4. call example:
$ ObjImg = new MyWaterDownChinese ();
$ ObjImg-> Path = "images /";
$ ObjImg-> FileName = "1.jpg ";
$ ObjImg-> Text = "HAHAKONGJIAN [url] HTTP: // HI. BAIDU. COM/LYSONCN [/url]";
$ ObjImg-> Font = "./font/simhei. ttf ";
$ ObjImg-> Run ();
** Member functions:
----------------------------------------------------------------*/
Class MyWaterDownChinese {
Var $ Path = "./"; // relative Path of the image directory to the page that calls this class
Var $ FileName = ""; // The name of the image, for example, JPG"
Var $ Text = ""; // The watermark Text to be added to the image. Chinese characters are supported.
Var $ TextColor = "# ffffff"; // text color. the font color must be black when the GIF image is used.
Var $ TextBgColor = "#000000"; // The color of the text background bar
Var $ Font = "c: // windows // fonts // simhei. ttf"; // Directory for storing fonts, relative path
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"
Var $ BaseWidth = 200; // The watermark text is added only when the image width is greater than or equal to 200.
//------------------------------------------------------------------
// Function: constructor of the class (php5.0 or above)
// Parameter: None
// Return: None
Function _ construct (){;}
//------------------------------------------------------------------
// Function: class destructor (php5.0 or above)
// Parameter: None
// Return: None
Function _ destruct (){;}
//------------------------------------------------------------------
//------------------------------------
// Function: run the object function and add a watermark to the image.
// Parameter: None
// Return: None
Function Run ()
{
If ($ this-> FileName = "" | $ this-> Text = "")
Return;
// Check whether the GD Library is installed
If (false = function_exists ("gd_info "))
{
Echo "the GD library is not installed in the system, and watermarks cannot be added to images .";
Return;
}
// Set the input and output image pathnames
$ Arr_in_name = explode (".", $ this-> FileName );
//
$ InImg = $ this-> Path. $ this-> FileName;
$ OutImg = $ inImg;
$ TmpImg = $ this-> Path. $ arr_in_name [0]. "_ tmp.". $ arr_in_name [1]; // temporarily processed image, very important
If (! $ This-> OverFlag)
$ OutImg = $ this-> Path. $ arr_in_name [0]. "_ water_down.". $ arr_in_name [1];
// Check whether the image exists
If (! File_exists ($ inImg ))
Return;
// Obtain Image attributes
$ GroundImageType = @ getimagesize ($ inImg );
$ ImgWidth = $ groundImageType [0];
$ ImgHeight = $ groundImageType [1];
$ ImgType = $ groundImageType [2];
If ($ imgWidth <$ this-> BaseWidth) // smaller than the basic width, not processed
Return;
// When the image is not jpg/jpeg/gif/png, it is not processed
Switch ($ imgType)
{
Case 1:
$ Image = imagecreatefromgif ($ inImg );
$ This-> TextBgColor = "# ffffff"; // The GIF image font can only be black, so the background color is white.
Break;
Case 2:
$ Image = imagecreatefromjpeg ($ inImg );
Break;
Case 3:
$ Image = imagecreatefrompng ($ inImg );
Break;
Default:
Return;
Break;
}
// Create a color
$ Color = @ imagecolorallocate ($ image, hexdec (substr ($ this-> TextColor, 1, 2), hexdec (substr ($ this-> TextColor, 3, 2 )), hexdec (substr ($ this-> TextColor, 5, 2); // text color
// Generate an empty image. its height increases the watermark height at the bottom.
$ NewHeight = $ imgHeight + 20;
$ ObjTmpImg = @ imagecreatetruecolor ($ imgWidth, $ newHeight );
$ ColorBg = @ imagecolorallocate ($ objTmpImg, hexdec (substr ($ this-> TextBgColor, 1, 2), hexdec (substr ($ this-> TextBgColor, 3, 2 )), hexdec (substr ($ this-> TextBgColor, 5, 2); // background color
// Fill in the background color of the image
@ Imagefill ($ objTmpImg, 0, 0, $ colorBg );
// Copy the source image to the temporary Image
@ Imagecopy ($ objTmpImg, $ image, 0, 0, 0, $ imgWidth, $ imgHeight );
// Create the watermark text object to be written
$ ObjText = $ this-> createText ($ this-> Text );
// Calculate the position of the watermark text to be written
$ X = 5;
$ Y = $ newHeight-5;
// Write a text watermark
@ Imagettftext ($ objTmpImg, 10, 0, $ x, $ y, $ color, $ this-> Font, $ objText );
// Generate a new image and a temporary Image
Switch ($ imgType)
{
Case 1:
Imagegif ($ objTmpImg, $ tmpImg );
Break;
Case 2:
Imagejpeg ($ objTmpImg, $ tmpImg );
Break;
Case 3:
Imagepng ($ objTmpImg, $ tmpImg );
Break;
Default:
Return;
Break;
}
// Release resources
@ Imagedestroy ($ objTmpImg );
@ Imagedestroy ($ image );
// Rename the file
If ($ this-> OverFlag)
{
// Overwrite the source image
@ Unlink ($ inImg );
@ Rename ($ tmpImg, $ outImg );
}
Else
{
// Do not overwrite the source image
@ Rename ($ tmpImg, $ outImg );
}
}
//--------------------------------------
// Function: Create a watermark text object
// Parameter: None
// Return: the created watermark text object.
Function createText ($ instring)
{
$ Outstring = "";
$ Max = strlen ($ instring );
For ($ I = 0; $ I <$ max; $ I ++)
{
$ H = ord ($ instring [$ I]);
If ($ h >=160 & $ I <$ MAX-1)
{
$ Outstring. = "&#". base_convert (bin2hex (iconv ("gb2312", "UCS-2", substr ($ instring, $ I, 2), 16, 10 ). ";";
$ I ++;
}
Else
{
$ Outstring. = $ instring [$ I];
}
}
Return $ outstring;
}
} // Class
?>

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.