PHP image processing class library and demo _ php instance

Source: Internet
Author: User
Tags imagejpeg
Recently, we need to study and study image processing. The first task is to select a suitable class library for image processing. Therefore, I wrote a simple example by referring to other class libraries. I only created images for specified text content (Chinese characters are not supported), created Verification Code images, and created thumbnails. For more information, see. I simply wrote a PHP image processing class library. Although it has few functions, it is not very advanced at present. I will use it later, or which of the following functions can I add to my suggestion, if you want to extend the class library, I have time to add it. If you want to extend the class library, you can share it with me. The code can be used now, there are not many things to consider. Please let me know if you have any better suggestions. Thank you.

Img. php

<? Php/*** Created by PhpStorm. * User: MCtion * Date: 2015/5/14 0014 * Time: * simple image class library. All relative paths in this class are based on the website root directory. If you need to modify them, modify constant _ WEBROOT _. * function: Specify the text content to create an image (Chinese is not supported), create a verification code image, create a thumbnail, and other functions to be continued * method: * Style (array $ Options) sets the image Style. Before each setting, it is reset to the default Style * Create_Img_Png () to create a PNG image. The related attributes are specified by the Style * Create_Img_Jpeg () to create a JPEG image, the related attributes are specified by the Style * Create_Verify () to create the verification code image. The related attributes are specified by the Style * Get_Verify () to obtain the value of the created verification code. MD5 encryption * Load_Img (string $ F IlePath) loads the image and creates an image source for other methods to call the source. FilePath is the relative path of the image * Create_Thumb (string $ FileName, string $ FilePath) created by Load_Img () the thumbnail of the loaded image. FileName indicates the prefix of the saved image. FilePath indicates the relative path of the saved image, excluding the file name (for example,/Uploads/images/Thumb /) */if (! Defined ("_ WEBROOT _") define ("_ WEBROOT _", $ _ SERVER ['document _ root']); class Img {protected $ _ Img; // image source protected $ _ FileImg; // The loaded image source protected $ _ FileInfo; // The information array of the loaded image protected $ _ PicInfo; // The information array of the loaded image's width and height protected $ _ Rand = 'abcdefghijkmnopqrstuvwxyzabcdefghjklmnopqrstuvwxyz1234567890 '; // random factor protected $ _ Code = ''; // verification Code public $ Width = 300; // The default Width of the image is public $ Height = 80; // The default Height of the image is public $ Backgro UndColor = "000000"; public $ Font = "/phps/Public/Font/ARIALNB. TTF "; // default font: public $ FontSize = 16; // default font size: public $ FontColor =" ffffff "; // default font color: public $ Content =" Test Word "; public $ Align = "left"; public $ Codes = 4; // number of verification Codes public $ Line = 6; // Number of interfering lines public $ LoadErr = ''; // error message // public function _ construct () {}/ ** set image properties * @ param array $ Options attribute array * @ return $ this returns the object */public function Style ($ Options) {$ this-> _ Re_Set (); foreach ($ Options as $ K => $ V) {if (in_array ($ K, array ('width', 'height', 'backgroundcolor', 'font', 'fontsize', 'fontcolor', 'content', 'align ', 'code ', 'line', 'snow') {if ($ K = "BackgroundColor" | $ K = "FontColor ") {if (preg_match ("# ([a-zA-Z0-9] {6}) #", $ V) $ this-> $ K = $ V ;} else {$ this-> $ K = $ V ;}} return $ this;}/*** reset attribute, no external access */protected function _ Re_Set () {$ This-> Width = 100; $ this-> Height = 30; $ this-> BackgroundColor = "000000 "; $ this-> Font = "/phps/Public/Font/ARIALNB. TTF "; $ this-> FontSize = 16; $ this-> FontColor =" ffffff "; $ this-> Align =" left "; $ this-> Codes = 4; $ this-> Line = 6 ;} /*** create an image source, add a background, and create an image * @ param bool $ BGC specify whether to create the background color and rectangular block */protected function _ Create_Img_GB ($ BGC = True) {$ this-> _ Img = imagecreatetruecolor ($ thi S-> Width, $ this-> Height); // create a back scene source if ($ BGC) {preg_match ("# ([a-zA-Z0-9] {2 }) ([a-zA-Z0-9] {2}) ([a-zA-Z0-9] {2}) # ", $ this-> BackgroundColor, $ ColorArr ); // separate the Color values into three groups of hexadecimal numbers $ Color = imagecolorallocate ($ this-> _ Img, hexdec ($ ColorArr [1]), hexdec ($ ColorArr [2]), hexdec ($ ColorArr [3]); // Add the background color imagefilledrectangle ($ this-> _ Img, 0, $ this-> Height, $ this-> Width, 0, $ Color); // create an image}/*** create a random Verification Code */prote Cted function _ Create_Code () {$ Len = strlen ($ this-> _ Rand)-1; for ($ I = 0; $ I <$ this-> Codes; $ I ++) {$ this-> _ Code. = $ this-> _ Rand [mt_rand (0, $ Len)] ;}}/*** write strings to the image. Chinese characters */protected function _ Write_Text () are not supported currently () {$ FontWidth = imagefontwidth ($ this-> FontSize); // obtain the width of a character in the font size, preg_match_all ('/(.) /us ', $ this-> Content, $ TextArr); // separate the Content into an array to calculate the number of times. $ FontHeight = imagefontheight ($ this-> FontSize ); // Get the font size height $ X = ceil ($ this-> Width-($ FontWidth * count ($ TextArr [0])/2 ); // set the distance between the X axis and the left side. $ Y = ceil ($ this-> Height + $ FontHeight)/2 ); // set the distance from the Y axis to the top margin preg_match ("# ([a-zA-Z0-9] {2}) ([a-zA-Z0-9] {2}) ([a-zA-Z0-9] {2 })#", $ this-> FontColor, $ ColorArr); $ Color = imagecolorallocate ($ this-> _ Img, hexdec ($ ColorArr [1]), hexdec ($ ColorArr [2]), hexdec ($ ColorArr [3]); // sets the text color imagettftext ($ this-> _ Img, $ thi S-> FontSize, 0, $ X, $ Y, $ Color ,__ WEBROOT __. $ this-> Font, $ this-> Content); // write Content}/*** write verification code to the image */protected function _ Write_Code () {$ _ X = $ this-> Width/$ this-> Codes; // set the Width to height ratio for ($ I = 0; $ I <$ this-> Codes; $ I ++) {// cyclically Codes, each time a verification code value $ Color = imagecolorallocate ($ this-> _ Img, mt_rand (0,156), mt_rand (0,156) is generated ), mt_rand (0,156); // the color of the randomly generated verification code value imagettftext ($ this-> _ Img, $ this-> FontSize, mt_rand (- 30,30), $ _ X * $ I + mt_rand (1.3), $ this-> Height/, $ Color ,__ WEBROOT __. $ this-> Font, $ this-> _ Code [$ I]); // generate a verification code value}/*** write interference lines to the image */protected function _ Write_Line () {// generate interference lines for ($ I = 0; $ I <$ this-> Line; $ I ++) {$ Color = imagecolorallocate ($ this-> _ Img, mt_rand (0,156), mt_rand (0,156 ), mt_rand (0,156); imageline ($ this-> _ Img, mt_rand (0, $ this-> Width), mt_rand (0, $ this-> Height ), mt_rand (0, $ this -> Width), mt_rand (0, $ this-> Height), $ Color) ;}/ *** set the image type to JPEG */protected function _ Img_Jpeg () {header ('content-type: image/jpeg '); imagejpeg ($ this-> _ Img); imagedestroy ($ this-> _ Img );} /*** set the image type to PNG */protected function _ Img_Png () {header ('content-type: image/png '); imagepng ($ this-> _ Img); imagedestroy ($ this-> _ Img);}/*** create JPEG string image */public function Create_Img_Jpg () {$ this-> _ Create_Img_GB (True); $ this-> _ Write_Text (); $ this-> _ Img_Jpeg ();} /*** create a PNG string image */public function Create_Img_Png () {$ this-> _ Create_Img_GB (True); $ this-> _ Write_Text (); $ this-> _ Img_Png ();}/*** create a PNG image of the Verification Code */public function Create_Verify () {$ this-> BackgroundColor = ''; for ($ I = 0; $ I <3; $ I ++) {$ this-> BackgroundColor. = dechex (mt_rand (20,155);} $ this-> _ Create_Img_GB (True ); $ This-> _ Create_Code (); $ this-> _ Write_Line (); $ this-> _ Write_Code (); $ this-> _ Img_Png ();} /*** obtain the MD5 encrypted Verification Code externally * @ return string */public function Get_Verify () {return md5 ($ this-> _ Code );} /*** load an image file and obtain image-related information * @ param string $ FilePath: The relative path of the image * @ return $ this | the bool returns an object, otherwise, FALSE */public function Load_Img ($ FilePath) {$ FilePath = _ WEBROOT _ is returned __. $ FilePath; if (! Is_file ($ FilePath) {$ this-> LoadErr = "path error, file does not exist"; Return False ;}$ this-> _ PicInfo = getimagesize ($ FilePath ); $ this-> _ FileInfo = pathinfo ($ FilePath); switch ($ this-> _ PicInfo [2]) {case 1: $ this-> _ FileImg = imagecreatefromgif ($ FilePath); break; case 2: $ this-> _ FileImg = imagecreatefromjpeg ($ FilePath); break; case 3: $ this-> _ FileImg = imagecreatefrompng ($ FilePath); break; default: $ this-> LoadErr = "Type error, unsupported image type"; Return False;} Return True ;} /*** create a thumbnail * @ param string $ prefix of the image name saved by FileName * @ param string $ FilePath: Save the relative path of the image * @ return mixed returns the array of information of the generated image * /public function Create_Thumb ($ FileName, $ FilePath) {$ SavePath = _ WEBROOT __. $ FilePath; if (! File_exists ($ SavePath) {mkdir ($ SavePath, 0777, true);} $ FileName = $ FileName. date ("YmdHis "). rand (100,999 ). '. '. $ this-> _ FileInfo ['extension']; $ FilePath = $ FilePath. $ FileName; $ SavePath = $ SavePath. $ FileName; $ this-> _ Create_Img_GB (False); imagecopyresampled ($ this-> _ Img, $ this-> _ FileImg, 0, 0, 0, 0, $ this-> Width, $ this-> Height, $ this-> _ PicInfo [0], $ this-> _ PicInfo [1]); switch ($ this-> _ PicInfo [2]) {case 1: imagegif ($ this-> _ Img, $ SavePath); break; case 2: imagejpeg ($ this-> _ Img, $ SavePath); break; case 3: imagepng ($ this-> _ Img, $ SavePath); break;} $ FIleInfo ['filename'] = $ FileName; $ FIleInfo ['filepath'] = $ FilePath; return $ FIleInfo ;}}

Example

$ Img = new Img (); $ Options ['width'] = 300; $ Options ['height'] = 100; $ Options ['content'] = "Test Create Img"; $ Options ['fontcolor'] = "FF0000"; $ Options ['backgroundcolor'] = "AAAAAA "; $ Img-> Style ($ Options)-> Create_Img_Jpg (); if ($ Img-> Load_Img ("/Public/images/ad1.png ")) {$ FileInfo = $ Img-> Style (array ('width' => 30, 'height' => 30)-> Create_Thumb ("Thumb ", "/Uploads/images/"); var_dump ($ FileInfo);} else {die ("image loading failed ,". $ Img-> LoadErr );}

The above is all the content of this article. I hope you will like it.

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.