GD Library Use Summary---2,GD summary---2_php tutorial

Source: Internet
Author: User
Tags imagecopy imagejpeg transparent color rtrim

GD Library Use Summary---2,GD summary---2


Then the previous article. GD Library can toss a lot of usage out, of course, with drawing related, in addition to the previous verification code, watermark, can also be scaled image, cutting, rotation and other operations, which can be seen in many applications.

1. Add watermark

As already known, we can use Imagechar or imagestring such as character or string (even Chinese characters) to draw to the image, in order to achieve the purpose of the watermark, there is a better way, not only to add the word character, but also to add a picture watermark: imagecopy.

Prototypes: BOOL Imagecopy (Resource $DST _im, resource $src _im, int $dst _x, int $dst _y, int $src _x, int $src _y, int $src _w, int $src _h), to see the name know this is copied, the 1th, 2 parameters are the target image handle, the source file handle, add watermark, if the watermark picture is a small picture, plus a large image above, then the first parameter is a large image handle, the second parameter is a small picture handle. 3rd, 4 parameters are the watermark on the target image x, y coordinate values, the 5th, 6 parameters are the watermark image start X, y coordinate values, 7th, 8 parameters are watermark image is going to be as the width and height of the watermark, so this method means that the watermark image Src_im upper left corner vertex coordinates (src_x, src_y), the width and height are src_w, src_h parts copied to the image dst_im, and then the DST_IM image to the canvas to save or output, that is, after the watermark is added to the image, code:

 PHP Date_default_timezone_set (' Asia/shanghai '); Define(' DS ',directory_separator); //add watermark, text, picture watermark, take picture as example    functionWatermark$srcFile= '',$markFile= '',$dstFile= '')    {        if(!file_exists($srcFile) || !file_exists($markFile))        {            Echo' File not exists!
'; return false; } //Get the width height of the original picture and the watermark picture List($srcWidth,$srcHeight) =getimagesize($srcFile); List($markWidth,$markHeight) =getimagesize($markFile); //watermark picture can't be bigger than original picture pixel if($markWidth>$srcWidth||$markHeight>$srcHeight) { return false; } //gets the original picture handle, watermark picture handle that will be watermarked $dstImg= Imagecreatefromjpeg ($srcFile); $markImg= Imagecreatefrompng ($markFile); //the location of the watermark, simply put it in the lower right corner $DST _x=$srcWidth-$markWidth; $DST _y=$srcHeight-$markHeight; //Get file Information $fileinfo=PathInfo($srcFile); if(Empty($dstFile)) { $dstFile=RTrim($fileinfo[' DirName '], DS). DS. ' Mark_ '.$fileinfo[' filename '].Date(' Ymdhis ').Mt_rand(1, 1000). '. Jpeg; } //copy a watermark picture to an existing pictureImagecopy ($dstImg,$markImg,$DST _x,$DST _y, 0, 0,$srcWidth,$srcHeight); //Save the newly added watermark image .Imagejpeg ($dstImg,$dstFile); Imagedestroy ($dstImg); Imagedestroy ($markImg); return true; } $srcFile= ' G:\wamp\www\html\image\p125.jpg ';//Original picture $markFile= ' G:\wamp\www\html\image\ooopic_5.png ';//Watermark PictureWatermark$srcFile,$markFile);

Effect:

Here, the watermark image is simply placed in the lower right corner of the picture, so put in the lower right corner of the picture to a simple calculation, call Imagecopy, from the top left corner of the watermark image (coordinate 0,0) start all (wide high watermark image width high) copied to the image to be added watermark, Then imagejpeg to draw the image and save, note that similar to imagejpeg (here simply use it), such as the drawing function when the second parameter is to save the picture as a file, rather than output to the browser, so do not need to adjust the header function to send header information.

Of course, you have to figure out which is the source file (SRC), which is the target file (DST), a small image watermark to a large map, the source file is a small image watermark, copy it to the large map, large map is the target.

can use the image as a watermark, in imagecopy the second parameter is the image handle, so you can create one from the existing picture (such as Imagecreatefromjpeg), Of course, you can also create a character image handle variable from an existing character---Use the imagecreatefromstring method, so this is more generic.

2. Image Zoom

Many applications, the picture list is a small map, when you click on a certain, will show a full large image, which involves a picture contraction processing. There are two ways to use it: imagecopyresized and imagecopyresampled, almost the same, unlike the latter, which re-sampled the image (which seems to be my professional word), so the image quality is better (resampling also depends on which method to take, some of which will become more slag), Pick one that says:

BOOL Imagecopyresampled (Resource $DST _image, resource $src _image, int $dst _x, int $dst _y, int $src _x, int $src _y, int $DST _w, int $dst _h, int $src _w, int $src _h)

The first to second parameter is similar to the above, how to zoom? For example here, the original image on the upper left corner of the vertex, coordinates (src_x, src_y), the width of the height of src_w, src_h part of the picture, draw to the target image coordinates (dst_x, dst_y), wide height for dst_w, Dst_h Place, So if the width and height ratio on the target image is selected for the width of the GAO Xiao, it will be reduced to a smaller version, and of course the coordinates of the top left-hand corner of the two are the same, with the JPG type as an example:

 PHP Date_default_timezone_set (' Asia/shanghai '); Define(' DS ',directory_separator); //Zoom Out Picture    /** * @param src Original image path * @param percent Zoom Out * @param dstfile Save the path to the picture*/    functionZoompic ($srcFile= '',$percent= 0.5,$dstFile= '')    {        if(!file_exists($srcFile))        {            return false; }        List($width,$height) =getimagesize($srcFile);//Get Wide height($percent<= 0 | |$percent> 1) &&$percent= 0.5; $newWidth= Floor($width*$percent);//reduced width and height        $newHeight= Floor($height*$percent); $dstImg= Imagecreatetruecolor ($newWidth,$newHeight);//Create a new canvas with a high image width        $srcImg= Imagecreatefromjpeg ($srcFile);//Create a canvas from the original image file                $pathinfo=PathInfo($srcFile); if(!$dstFile)$dstFile=RTrim($pathinfo[' DirName '], DS). DS. ' Zoom_ '.$pathinfo[' filename '].Date(' Ymdhis ').Mt_rand(1, 1000). ". Jpeg; //zoom in from the top left corner of the source file//imagecopyresized ($dstImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); Imagecopyresampled ($dstImg,$srcImg, 0, 0, 0, 0,$newWidth,$newHeight,$width,$height); //drawing and saving imagesImagejpeg ($dstImg,$dstFile); //Destroying ResourcesImagedestroy ($dstImg); Imagedestroy ($srcImg); return true; }    //Test    $srcFile= ' G:\wamp\www\html\image\p179.jpg '; Zoompic ($srcFile);

Effect:

Here, we can be two sets of original image and small map storage, a list of small images, low-level check to show the original.

3. Picture clipping

Consider the above imagecopyresampled method, if you do not start from the upper left corner of the original image, but the upper left corner of the lower right to start a point, the width of the graph is also equal to the full width of the source file, but part of the width of the high, then the new resampling of the picture, is a part of the source image, to achieve the So cropping and zooming use the same way

  

 PHP Date_default_timezone_set (' Asia/shanghai '); Define(' DS ',directory_separator); //cut a picture    functionCutpic ($srcFile= '',$x= 0,$y= 0,$width= 16,$height= 16,$dstFile= '')    {        if(!file_exists($srcFile))        {            return false; }        List($srcWidth,$srcHeight,$type) =getimagesize($srcFile); $x< 0 &&$x= 0; $y< 0 &&$y= 0; //Wide Height setting(($width+$x) >$srcWidth) &&$width=$srcWidth; (($height+$y) >$srcHeight) &&$height=$srcHeight; ($width<= 0) &&$width=$srcWidth; ($height<= 0) &&$height=$srcHeight; $dstImg= Imagecreatetruecolor ($width,$height);//Target file Resource        Switch($type)        {             CaseImg_gif:$srcImg= Imagecreatefromgif ($srcFile);//Gets the source file resource handle and extension processing to use the appropriate function and extension                $ext= ' gif '; $imagefun= ' Imagegif ';  Break;  CaseImg_jpg:$srcImg= Imagecreatefromjpeg ($srcFile); $ext= ' jpeg '; $imagefun= ' imagejpeg ';  Break; default:$srcImg= Imagecreatefrompng ($srcFile); $ext= ' png '; $imagefun= ' Imagepng ';  Break; }        //set the file path after saving the cut        $fileinfo=PathInfo($srcFile); if(Empty($dstFile))        {            $dstFile=RTrim($fileinfo[' DirName '], DS). DS. ' Cut_ '.$fileinfo[' filename '].Date(' Ymdhis ').Mt_rand(1, 1000). ". {$ext}"; }        //perform a cut operationImagecopyresampled ($dstImg,$srcImg, 0, 0,$x,$y,$width,$height,$width,$height); //draw on canvas and save files        $imagefun($dstImg,$dstFile); Imagedestroy ($dstImg); Imagedestroy ($srcImg); return true; }    //Test    $srcFile= ' G:\wamp\www\html\image\p221.jpg '; Cutpic ($srcFile, 50, 50, 50, 50);

Effect:

The common application is that when we change the avatar for one of our own applications, the avatar is too big to be used for clipping, so we can do a simulation.

4. Picture rotation

Picture rotation is also very common, mainly used in function imagerotate, prototype: Resource Imagerotate (Resource $image, float $angle, int $bgd _color [, int $ignore _trans Parent = 0]), the first parameter is the image handle to be rotated, the second parameter angle is the angular value of the rotation, the third parameter specifies a color, that is, when the empty space after the rotation is used to fill the color, the fourth parameter is to specify a transparent color, the default of 0 is to preserve the transparent color. This method returns a new image handle, which is the image resource variable after the rotation, and it is drawn and saved. Also note that the angle of rotation can be specified between 0 and 360, counterclockwise rotation, with JPG as an example:

 PHP Date_default_timezone_set (' Asia/shanghai '); Define(' DS ',directory_separator); /** * Picture rotation * @param angular rotation angle value 0-360*/    functionRotatepic ($srcFile= '',$angular= 0,$dstFile= '')    {        if(!file_exists($srcFile))        {            Echo' File NOT exists
'; return false; } $srcImg= Imagecreatefromjpeg ($srcFile); //process Save File Address $fileinfo=PathInfo($srcFile); if(Empty($dstFile)) { $dstFile=RTrim($fileinfo[' DirName '], DS). DS. ' Rotate_ '.$fileinfo[' filename '].Date(' Ymdhis ').Mt_rand(1, 1000). '. Jpeg; } $white= Imagecolorallocate ($srcImg, 0xFF, 0xFF, 0xf1); //perform the rotation, note the counterclockwise direction $dstImg= Imagerotate ($srcImg,$angular,$white); //draw to canvas, save fileImagejpeg ($dstImg,$dstFile); Imagedestroy ($dstImg); Imagedestroy ($srcImg); return true; } //Test $srcFile= ' G:\wamp\www\html\image\p219.jpg '; Rotatepic ($srcFile, 220);

Effect: After the original is rotated

5. Picture flipping

This is less common in applications. The so-called Flip, is to mirror the image to flip, for example, the image of the middle vertical line for the axis, the left to the right, to the right to the left, to change the position, is the left and the reverse. Imagine, with the middle vertical line as the symmetric axis, the y-axis pixel is unchanged, the x-axis pixels on the right and left, you can still use the Imagecopy method, for the source file, when copied to the target image, this operation to rotate around the y axis, jpg type picture as an example

 Php//Picture FlippingDate_default_timezone_set (' Asia/shanghai '); Define(' DS ',directory_separator); //flips along the y-axis, and the x-coordinate value is swapped    functionTurny ($srcFile= '',$dstFile= '')    {        if(!file_exists($srcFile))        {            return false; }        //the original image handle and the wide-height get        $srcImg= Imagecreatefromjpeg ($srcFile); $srcWidth= Imagesx ($srcImg); $srcHeight= Imagesy ($srcImg); $dstImg= Imagecreatetruecolor ($srcWidth,$srcHeight); //flips along the y-axis, and the pixels on the x-axis are swapped around .         for($i= 0;$i<$srcWidth;$i++) {imagecopy ($dstImg,$srcImg,$srcWidth-$i-1, 0,$i, 0, 1,$srcHeight); }        //image save path processing        $fileinfo=PathInfo($srcFile); if(Empty($dstFile))        {            $dstFile=RTrim($fileinfo[' DirName '], DS). DS. ' Turnx_ '.$fileinfo[' filename '].Date(' Ymdhis ').Mt_rand(1, 1000). '. Jpeg; }        //drawing images, saving filesImagejpeg ($dstImg,$dstFile); Imagedestroy ($dstImg); Imagedestroy ($srcImg); return false; }        //Test    $srcFile= ' G:\wamp\www\html\image\p311.jpg '; Turny ($srcFile);

Effect: After flipping before flipping

Mainly for loop there, after getting the width of the source file $srcwidth, if the coordinates on the source file ($i, 0) correspond to the coordinates on the target image ($srcWidth-$i-1, 0), then the width is 1 pixels, the height of the source file is $ Srcheight Resources copied in the past, after the completion of the cycle is all copied to a picture, the equivalent of a line of painting past.

No intention to browse the manual feeling by the pit, see imageflip function guess is this function, a see sure is true, but read the book has been behind a few years, prototype: BOOL Imageflip (Resource $image, int $mode), the first parameter is the target image resource, The second parameter is the way to flip, using PHP's own enumeration variables can be img_flip_horizontal (horizontal), img_flip_horizontal (vertical), img_flip_both (horizontal vertical) Three ways, a function can be achieved.

Anyway is very simple, better practice practiced hand play:-D

http://www.bkjia.com/PHPjc/992389.html www.bkjia.com true http://www.bkjia.com/PHPjc/992389.html techarticle GD Library Use summary---2,GD summary---2 then the previous article. GD Library can toss a lot of usage out, of course, with drawing related, in addition to the previous verification code, watermark, you can also take pictures of ...

  • Related Article

    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.