Php image function example (non-original) _ PHP Tutorial

Source: Internet
Author: User
Tags 0xc0 image identifier imagejpeg random seed
Php image function example (not original ). The following is a method: if (! Function_exists (imagecreate) {die (this server does not support the GD module);} if not, how can I configure it? Download the dll file of the gd module and modify the php The following is a method:
If (! Function_exists ('imagecreate ')){
Die ('the current server does not support GD module ');
}
If not, how can I configure it? Download the dll file of the gd module, modify php. ini, and restart the server.
The PHP plot is PS.
When you plan to PS, you should complete the following steps, which is necessary.
1: Create a basic PS object (I suppose it is $ image) and fill in the background (Black by default). all subsequent ps operations will be based on this background image.
2: Plot on $ image.
3: output this image.
4. destroy objects and clear memory usage.
First, let's get to know several common functions. these functions are described in detail in the php Manual.
Resource imagecreate (int x_size, int y_size)
Imagecreate () returns an image identifier, representing a blank image of x_size and y_size.
This function is basically the same as imagetruecolor ($ width, $ height ).
---------------------------------------------------------
Int imagecolorallocate (resource image, int red, int green, int blue)
Imagecolorallocate () returns an identifier representing a color consisting of a given RGB component. The image parameter is the return value of the imagecreatetruecolor () function. Red, green, and blue are the required colors respectively. These parameters are integers from 0 to 255 or hexadecimal values 0x00 to 0xFF. Imagecolorallocate () must be called to create the color of each image used in the image.
---------------------------------------------------------
Bool imagefill (resource image, int x, int y, int color)
Imagefill () is filled with the color execution area (that is, with x, y points are in the same color and adjacent points are filled ).
---------------------------------------------------------
Bool imageline (resource image, int x1, int y1, int x2, int y2, int color)
Imageline () uses color to draw a line segment from the coordinates x1, y1 to x2, y2 (0 in the upper left corner of the image.
---------------------------------------------------------
Bool imagestring (resource image, int font, int x, int y, string s, int col)
Imagestring () uses the col color to draw string s to the x and y coordinates of the image (this is the coordinate of the upper left corner of the string, and the upper left corner of the entire image is 0, 0 ). If the font is 1, 2, 3, 4, or 5, the built-in font is used.
---------------------------------------------------------
Array imagettftext (resource image, float size, float angle, int x, int y, int color, string fontfile, string text)
This function is important and has many parameters. it is not listed here. it is mainly written to an image. it is similar to the above function, but must be powerful.
---------------------------------------------------------
Bool imagefilltoborder (resource image, int x, int y, int border, int color)
Imagefilltoborder () starts from x, y (0, 0 in the upper left corner of the image) and fills the area with color until the border of the color is border is reached. [Note: all colors in the boundary are filled. If the specified boundary color is the same as that of the vertex, it is not filled. If this boundary color does not exist in the image, the entire image will be filled .]
------------------------------------------------
Bool imagefilledellipse (resource image, int cx, int cy, int w, int h, int color)
Imagefilledellipse () draws an elliptical image centered on cx and cy (0, 0 in the upper left corner of the image. W and h specify the width and height of the elliptic respectively. Fill the ellipse with color. If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
========================================================== ==========
Output image data: imagepng ($ image [, $ filename])
========================================================== ====================
Example 1: output blue background and cross white line graphics
$ Width = 35;
$ Height = 35;
// Create an object
$ Image = imagecreate ($ width, $ height );
// Extract color
$ Color_white = imagecolorallocate ($ image, 255,255,255); // White
$ Color_blue = imagecolorallocate ($ image, 108,); // Blue
Imagefill ($ image, 0, 0, $ color_blue );
// Plot
// Line width
Imagesetthickness ($ image, 3 );
Imageline ($ image, 0, 0, $ width, $ height, $ color_white );
Imageline ($ image, $ width, 0, 0, $ height, $ color_white );
// Send the object to the header
Header ('content-type: image/png ');
Imagepng ($ image );
/*
// Send an object to a file
$ Filename = "ex1.png ";
Imagepng ($ image, $ filename );
*/
// Destroy the object
Imagedestroy ($ image );
?>
Output Image:
Online demo: http://www.phzzy.org/temp/5do8/ex1.php
Example 2: yin/yang diagram
$ Width = 400;
$ Height = 400;
$ Image = imagecreatetruecolor ($ width, $ height );
// Extract color
$ Color_black = imagecolorallocate ($ image, 0, 2, 0 );//
$ Color_white = imagecolorallocate ($ image, 255,255,255); // White
$ Color_blue = imagecolorallocate ($ image, 108,); // Blue
$ Color_red = imagecolorallocate ($ image, 151,0, 4); // Red
$ Color_my = imagecolorallocate ($ image, 192,192,255); // background
$ Color_temp = imagecolorallocate ($ image, 199,199,199); // background
// Plot
Imagefill ($ image, 0, 0, $ color_white );
// The first one is a big circle.
Imagefilledarc ($ image, $ width/2, $ height/2, $ height, $ height, 0,360, $ color_blue, IMG_ARC_PIE );
// Two Circles
Imagefilledellipse ($ image, $ width/2, $ height/4, $ height/2, $ height/2, $ color_red );
Imagefilledellipse ($ image, $ width/2, $ height/4*3, $ height/2, $ height/2, $ color_blue );
/* Imagefilledellipse -- draw an ellipse and fill it */
Imagefilledarc ($ image, $ width/2, $ height/2, $ height, $ height,-90, $ color_red, IMG_ARC_PIE );
Imagefilledellipse ($ image, $ width/2, $ height/4*3, $ height/2, $ height/2, $ color_blue );
// Send the object to the header
Header ('content-type: image/png ');
Imagepng ($ image );
/*
// Send an object to a file
$ Filename = "ex1.png ";
Imagepng ($ image, $ filename );
*/
// Destroy the object
Imagedestroy ($ image );
?>
Demo:
Http://www.phzzy.org/temp/5do8/ex2.php
Example 3: 3D images-cool
$ Width = 400;
$ Height = 400;
$ Image = imagecreatetruecolor ($ width, $ height );
$ White = imagecolorallocate ($ image, 0xFF, 0xFF, 0xFF );
$ Gray = imagecolorallocate ($ image, 0xC0, 0xC0, 0xC0 );
$ Darkgray = imagecolorallocate ($ image, 0x90, 0x90, 0x90 );
$ Navy = imagecolorallocate ($ image, 0x00, 0x00, 0x80 );
$ Darknavy = imagecolorallocate ($ image, 0x00, 0x00, 0x50 );
$ Red = imagecolorallocate ($ image, 0xFF, 0x00, 0x00 );
$ Darkred = imagecolorallocate ($ image, 0x90, 0x00, 0x00 );
Imagefill ($ image, 0, 0, $ white );
// Make the 3D effect
For ($ I = $ height/2 + 20; $ I >$ height/2; $ I --){
Imagefilledarc ($ image, $ width/2, $ I, $ width/2, $ height/2, 0, 45, $ darknavy, IMG_ARC_PIE );
Imagefilledarc ($ image, $ width/2, $ I, $ width/2, $ height/2, 45, 75, $ darkgray, IMG_ARC_PIE );
Imagefilledarc ($ image, $ width/2, $ I, $ width/2, $ height/2, 75,360, $ darkred, IMG_ARC_PIE );
}
Imagefilledarc ($ image, $ width/2, $ height/2, $ width/2, $ height/2, 0, 45, $ navy, IMG_ARC_PIE );
Imagefilledarc ($ image, $ width/2, $ height/2, $ width/2, $ height/2, 45, 75, $ gray, IMG_ARC_PIE );
Imagefilledarc ($ image, $ width/2, $ height/2, $ width/2, $ height/2, 75,360, $ red, IMG_ARC_PIE );
// Flush image
Header ('content-type: image/png ');
Imagepng ($ image );
Imagedestroy ($ image );
/*
// Send an object to a file
$ Filename = "ex1.png ";
Imagepng ($ image, $ filename );
*/
?>
Output:
Demo: http://www.phzzy.org/temp/5do8/ex3.php

Example 4: simple verification code
It is very easy to create a verification code in PHP. The simple idea is as follows:
Random seed generation, random characters are extracted, printed to the image, and output. to prevent color blindness, you can randomly extract colors or customize colors. let's take a look at the following:
Session_start ();
$ Width = 65;
$ Height = 20;
$ Sourcestrings = "0123456789 aqwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM ";
$ Image = imagecreate ($ width, $ height );
$ Colorarrs = array (
Imagecolorallocate ($ image, 255,255,255), // white
Imagecolorallocate ($ image, 0, 0, 0) // black
);
Unset ($ sessionval );
Imagesetthickness ($ image, 3 );
// Obtain the number of random strings
$ Strsize = rand (3, 5 );
Imagefill ($ image, 0, 0, $ colorarrs [0]);
// Write strings to images one by one
For ($ I = 0; $ I <$ strsize; $ I ++ ){
$ I _temp = rand (1, 62 );
$ Sessionval. = $ sourcestrings [$ I _temp];
$ Fontcolor = imagecolorallocate ($ image, rand (0,255), rand (0,255), rand (0,255 ));
$ Y_ I = $ height/2 + $ font_size/3;
Imagechar ($ image, 5, 1 + $ I * $ width/$ strsize, 5, $ sourcestrings [$ I _temp], $ fontcolor );
}
// Write the session and use it for future verification
Unset ($ _ SESSION ['cjer']);
$ _ SESSION ['cjer'] = $ sessionval;
// Add a miscellaneous
For ($ I = 0; $ I <$ width/$ height * 2; $ I ++)
{$ I _x = rand (0, $ width );
$ I _y = rand (0, $ height );
$ Pixelcolor = imagecolorallocate ($ image, rand (0,255), rand (0,255), rand (0,255 ));
Imagesetpixel ($ image, $ I _x, $ I _y, $ pixelcolor );
}
Header ('content-type: image/png ');
Imagepng ($ image );
Imagedestroy ($ image );
?>
Generate a style demonstration:
Online demo: http://www.phzzy.org/temp/5do8/ex4_login.php
The obvious problem is that the generated image is not gorgeous enough, so many users may not be clear about it. in this case, we can set several colorful colors and output them to expand the colorarrs array:
$ Colorarrs = array (
Imagecolorallocate ($ image, 255,255,255 ),
Imagecolorallocate ($ image, 0, 0 ),
Imagecolorallocate ($ image, 0, 70, 0 ),
Imagecolorallocate ($ image, 92,0, 12 ),
Imagecolorallocate ($ image, 128 ),
Imagecolorallocate ($ image, 23, 10, 216)
);
Then change 23 rows to (17 rows ):
$ Fontcolor = $ colorarrs [rand (1, count ($ colorarrs)-1)];
Output:
Online demo: http://www.phzzy.org/temp/5do8/ex5_login.php
Example 5: cool verification code
PS images are still relatively small, sometimes for some reason (for personal sites to play cool, just me, commercial sites to play style, attract users, just google, later ), the verification code is not limited to the limit of more than a dozen pixels. sometimes it can be more than two hundred million characters. there is no problem. at this time, a solution is to force the small image generated above to be larger, can it? Yes, but it does not look smooth enough. this is a fact. Obviously, broadband is no longer the most important issue. let's not talk about other issues. The following describes several nice-looking generation methods:
Session_start ();
$ Width = 600;
$ Height = 100;
If ($ height <$ width/6)
$ Height = $ width/4;
$ Sourcestrings = "0123456789 aqwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM ";
// Create an object
$ Image = imagecreate ($ width, $ height );
$ White = imagcolorallocate ($ image, 255,255,255 );
Imagefill ($ image, 0, 0, $ white );
// Load the font library
$ Fonts = dirname (_ FILE __);
Putenv ('"gdfontpath =". $ fonts = .""');
$ Fontname = 'arial ';
$ Font_size = floor ($ height/2 );
// Obtain the string
Unset ($ sessionval );
$ Strsize = rand (5, 8 );
For ($ I = 0; $ I <$ strsize; $ I ++ ){
$ I _temp = rand (1, 62 );
$ Sessionval. = $ sourcestrings [$ I _temp];
$ X_ I = $ font_size + $ I * $ width/($ strsize + 1 );
$ Y_ I = $ height/2;
$ Angle_ I = rand (-120,120 );
$ Fontcolor_a = imagecolorallocate ($ image, rand (0,255), rand (0,255), rand (0,255 ));
ImageTTFText ($ image, $ font_size, $ angle_ I, $ x_ I, $ y_ I, $ fontcolor_a, $ fontname, $ sourcestrings [$ I _temp]);
}
Unset ($ _ SESSION ['cjer']);
$ _ SESSION ['cjer'] = $ sessionval;
// Number of miscellaneous
For ($ I = 0; $ I <$ width * $ height/100; $ I ++)
{
$ I _x = rand (0, $ width );
$ I _y = rand (0, $ height );
Imagesetpixel ($ image, $ I _x, $ I _y, imagecolorallocate ($ image, rand (0,255), rand (0,255), rand )));
}
// Sending object
Header ('content-type: image/png ');
Imagepng ($ image );
Imagedestroy ($ image );
?>

Online test: http://www.phzzy.org/temp/5do8/ex6_login.php
Explanatory description:
The first is width and height, and the characters are too small to be clear. the number of randomly extracted characters is as follows:
$ Sourcestrings = "0123456789 aqwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM ";
Create an object and fill it in white:
$ Image = imagecreate ($ width, $ height );
$ White = imagcolorallocate ($ image, 255,255,255 );
Imagefill ($ image, 0, 0, $ white );
Then load the font of the verification code:
$ Fonts = dirname (_ FILE _); // returns the current root directory. copy the font FILE to this directory. the font FILE is *. ttf.
Putenv ('"gdfontpath =". $ fonts = .""');
$ Fontname = 'arial ';
Define the character height. here I set it to half of the height:
$ Font_size = floor ($ height/2 );
Clear the variable and randomly set the number of characters to be generated:
Unset ($ sessionval );
$ Strsize = rand (5, 8 );
Loop:
Get the string of this loop, and add it to the variable and write it to the session later.
$ I _temp = rand (1, 62 );
$ Sessionval. = $ sourcestrings [$ I _temp];
Get the position of the string written into the image (x and y coordinates)
$ X_ I = $ font_size + $ I * $ width/($ strsize + 1 );
$ Y_ I = $ height/2;
Set the inclination, which is visible on the front ,.
$ Angle_ I = rand (-120,120 );
Randomly generate colors,
$ Fontcolor_a = imagecolorallocate ($ image, rand (0,255), rand (0,255), rand (0,255 ));
Write to image;
ImageTTFText ($ image, $ font_size, $ angle_ I, $ x_ I, $ y_ I, $ fontcolor_a, $ fontname, $ sourcestrings [$ I _temp]);
If you have any questions about this function, please refer to the relevant information. it is very easy.
Write to the session and use the following registration code:
Unset ($ _ SESSION ['cjer']);
$ _ SESSION ['cjer'] = $ sessionval;
Add Miscellaneous:
// Number of miscellaneous
For ($ I = 0; $ I <$ width * $ height/100; $ I ++)
{
$ I _x = rand (0, $ width );
$ I _y = rand (0, $ height );
Imagesetpixel ($ image, $ I _x, $ I _y, imagecolorallocate ($ image, rand (0,255), rand (0,255), rand )));
}
Output to header:
Header ('content-type: image/png '); // This line indicates that it is a png image. it can be output by default, but it is not the header format of the image.
Imagepng ($ image );
Imagedestroy ($ image );
You can load your own library and set the rotation angle $ angle_ I = rand (-120,120); set the font height $ font_size = floor ($ height/2 ); font color $ fontcolor_a and the number of random numbers: $ strsize = rand (5, 8 );

Example 6: add a watermark to the image to generate a column chart
The traditional ASP page sub-watermark and the generation of column chart are cumbersome, generally use other components or something, but PHP can easily do these things, as you expected, for more than 30 lines of programs, see the source code:
$ Source = "my.jpg ";
$ Zoom = 0.5;
$ Str = 'I'm a handsome guy. are you MM? ';
$ Image = imagecreatefromjpeg ($ source );
$ Width = imagesx ($ image );
$ Height = imagesy ($ image );
$ Color_red = imagecolorallocate ($ image, 111,0, 0); // Red
$ Font = dirname (_ FILE _). "// simsun. ttc ";
$ Str = iconv ('gb2312', 'utf-8', $ str );
$ Fontsize = 30;
$ Angle = 25;
$ Fromx = $ width/5;
$ Fromy = $ height/2;
Imagettftext ($ image, $ fontsize, $ angle, $ fromx, $ fromy, $ color_red, $ font, $ str );
$ Width_temp = imagesx ($ image) * $ zoom;
$ Height_temp = imagesy ($ image) * $ zoom;
$ Img = imagecreatetruecolor ($ width_temp, $ height_temp );
Imagecopyresized ($ img, $ image, 0, 0, 0, $ width_temp, $ height_temp, $ width, $ height );
Imagedestroy ($ image );
$ File_zoomname = "my_zoom_jpeg.jpg ";
Imagejpeg ($ img, $ file_zoomname );
Imagedestroy ($ img );
?>
Original image:
JPG image generated:
70 K for the original image. here, if a gif is generated, more than 18 k for the file, and 76 K for the png image, we will generate a column chart in jpeg format.
Code analysis:
Here I first set several parameters:
$ Source = "my.jpg"; // source image
$ Zoom = 0.5; // zoom percentage
$ Str = 'I'm a handsome guy. are you MM? '; // Watermark text
Load source image (without watermarks or loading ):
$ Image = imagecreatefromjpeg ($ source );
Obtain the length and width:
$ Width = imagesx ($ image );
$ Height = imagesy ($ image );
Set the watermark font. because we use Chinese characters, we must import the Chinese character Library. Otherwise, we cannot write or garbled characters and must convert the string encoding.
$ Font = dirname (_ FILE _). "// simsun. ttc ";
$ Str = iconv ('gb2312', 'utf-8', $ str );
Set the start point, font size, angle of view:, write string:
$ Fontsize = 30;
$ Angle = 25;
$ Fromx = $ width/5;
$ Fromy = $ height/2;
Imagettftext ($ image, $ fontsize, $ angle, $ fromx, $ fromy, $ color_red, $ font, $ str );
Generate new large and small objects according to the scaling size requirement:
$ Width_temp = imagesx ($ image) * $ zoom;
$ Height_temp = imagesy ($ image) * $ zoom;
$ Img = imagecreatetruecolor ($ width_temp, $ height_temp );
Copy the source image to the new image. the imagecopyresized of the gd Library automatically scales
Imagecopyresized ($ img, $ image, 0, 0, 0, $ width_temp, $ height_temp, $ width, $ height );
Generate a small image and clear the object:
Imagedestroy ($ image );
$ File_zoomname = "my_zoom_jpeg.jpg ";
Imagejpeg ($ img, $ file_zoomname );
Imagedestroy ($ img );
The core technology of generating a scale-down image is like this.

Else if (! Function_exists ('imagecreate') {die ('This server does not support GD module');} if not, how can I configure it? Download the dll file of the gd module and modify php...

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.