Php saves images as image instances of different sizes

Source: Internet
Author: User
Tags transparent color
This article describes how php saves images of different sizes as image classes, involves common techniques such as saving, copying, and thumbnails of php images, and encapsulates them into a class file for ease of calling, it is of great practical value. if you need it, you can refer to the example in this article to describe how php saves images as different types of image classes. Share it with you for your reference. The details are as follows:

Image processing class. imagecls. php is as follows:

<? Php/** image processing class */class imagecls {/*** file information */var $ file = array (); /*** save directory */var $ dir = '';/*** error code */var $ error_code = 0; /*** maximum file Upload KB */var $ max_size =-1; function es_imagecls () {} private function checkSize ($ size) {return! ($ Size> $ this-> max_size) | (-1 = $ this-> max_size );} /*** process the uploaded file ** @ param array $ file the uploaded file * @ param string $ dir saved directory * @ return bool */function init ($ file, $ dir = 'temp ') {if (! Is_array ($ file) | empty ($ file) |! $ This-> isUploadFile ($ file ['tmp _ name']) | trim ($ file ['name']) = ''| $ file ['size'] = 0) {$ this-> file = array (); $ this-> error_code =-1; return false;} else {$ file ['size'] = intval ($ file ['size']); $ file ['name'] = trim ($ file ['name']); $ file ['thumb'] = ''; $ file ['text'] = $ this-> fileExt ($ file ['name']); $ file ['name'] = htmlspecialchars ($ file ['name'], ENT_QUOTES); $ file ['is _ image'] = $ this-> isImage Ext ($ file ['ext ']); $ file ['File _ dir'] = $ this-> getTargetDir ($ dir ); $ file ['prefix'] = md5 (microtime (true )). rand (10, 99); $ file ['target'] = ". /public /". $ file ['File _ dir']. '/'.20.file='prefix'0000.'.jpg'; // relative to $ file ['Local _ target'] = APP_ROOT_PATH. "public /". $ file ['File _ dir']. '/'.{file}'prefix'{.'.jpg'; // physical $ this-> file = & $ file; $ this-> error_code = 0; return true ;}} /*** save the file * @ return bool */function sa Ve () {if (empty ($ this-> file) | empty ($ this-> file ['tmp _ name']) $ this-> error_code =-101; elseif (! $ This-> checkSize ($ this-> file ['size']) $ this-> error_code =-105; elseif (! $ This-> file ['is _ image']) $ this-> error_code =-102; elseif (! $ This-> saveFile ($ this-> file ['tmp _ name'], $ this-> file ['Local _ target']) $ this-> error_code =-103; elseif ($ this-> file ['is _ image'] & (! $ This-> file ['image _ info'] = $ this-> getImageInfo ($ this-> file ['Local _ target'], true ))) {$ this-> error_code =-104; @ unlink ($ this-> file ['Local _ target']);} else {$ this-> error_code = 0; return true;} return false;}/*** get error code * @ return number */function error () {return $ this-> error_code ;} /*** get file extension * @ return string */function fileExt ($ file_name) {return addslashes (strtolower (substr (strrch R ($ file_name ,'. '), 1, 10 )));} /*** determine whether the file is an image based on the extension * @ param string $ ext extension * @ return bool */function isImageExt ($ ext) {static $ img_ext = array ('jpg ', 'jpeg', 'PNG ', 'bmp', 'GIF', 'giff '); return in_array ($ ext, $ img_ext )? 1: 0;}/*** obtain image information * @ param string $ target file path * @ return mixed */function getImageInfo ($ target) {$ ext = es_imagecls :: fileExt ($ target); $ is_image = es_imagecls: isImageExt ($ ext); if (! $ Is_image) return false; elseif (! Is_readable ($ target) return false; elseif ($ image_info = @ getimagesize ($ target) {list ($ width, $ height, $ type) =! Empty ($ image_info )? $ Image_info: array ('','', ''); $ size = $ width * $ height; if ($ is_image &&! In_array ($ type, array (, 13) return false; $ image_info ['type'] = strtolower (substr (image_type_to_extension ($ image_info [2]), 1); return $ image_info;} else return false ;} /*** obtain whether to upload a file. * @ param string $ source file path * @ return bool */function isUploadFile ($ source) {return $ source & ($ source! = 'None') & (is_uploaded_file ($ source) | is_uploaded_file (str_replace ('\\\\',' \', $ source )));} /*** get the saved path * @ param string $ dir the specified directory * @ return string */function getTargetDir ($ dir) {if (! Is_dir (APP_ROOT_PATH. "public /". $ dir) {@ mkdir (APP_ROOT_PATH. "public /". $ dir); @ chmod (APP_ROOT_PATH. "public /". $ dir, 0777);} return $ dir ;} /*** save the file * @ param string $ source file path * @ param string $ target directory file path * @ return bool */private function saveFile ($ source, $ target) {if (! Es_imagecls: isUploadFile ($ source) $ succeed = false; elseif (@ copy ($ source, $ target) $ succeed = true; elseif (function_exists ('move _ uploaded_file ') & @ move_uploaded_file ($ source, $ target) $ succeed = true; elseif (@ is_readable ($ source) & (@ $ fp_s = fopen ($ source, 'RB') & (@ $ fp_t = fopen ($ target, 'wb') {while (! Feof ($ fp_s) {$ s = @ fread ($ fp_s, 1024*512); @ fwrite ($ fp_t, $ s);} fclose ($ fp_s ); fclose ($ fp_t); $ succeed = true;} if ($ succeed) {$ this-> error_code = 0; @ chmod ($ target, 0644 ); @ unlink ($ source);} else {$ this-> error_code = 0;} return $ succeed;} public function thumb ($ image, $ maxWidth = 200, $ maxHeight = 50, $ gen = 0, $ interlace = true, $ filepath = '', $ is_preview = true) {$ info = es_imagecls: getImageInf O ($ image); if ($ info! = False) {$ srcWidth = $ info [0]; $ srcHeight = $ info [1]; $ type = $ info ['type']; $ interlace = $ interlace? 1:0; unset ($ info); if ($ maxWidth> 0 & $ maxHeight> 0) $ scale = min ($ maxWidth/$ srcWidth, $ maxHeight/$ srcHeight ); // calculate the scale of elseif ($ maxWidth = 0) $ scale = $ maxHeight/$ srcHeight; elseif ($ maxHeight = 0) $ scale = $ maxWidth/$ srcWidth; $ paths = pathinfo ($ image); $ paths ['filename'] = trim (strtolower ($ paths ['basename']), ". ". strtolower ($ paths ['extension']); $ basefilename = explode ("_", $ paths ['filename'] ); $ Basefilename = $ basefilename [0]; if (empty ($ filepath) {if ($ is_preview) $ thumbname = $ paths ['dirname']. '/'.w.basefilename.'_'.w.maxwidth.'x'.w.maxheight.'.jpg'; else $ thumbname = $ paths ['dirname']. '/'.w.basefilename.'o_'.w.maxwidth.'x'.w.maxheight.'.jpg';} else $ thumbname = $ filepath; $ thumburl = str_replace (APP_ROOT_PATH ,'. /', $ thumbname); if ($ scale> = 1) {// no longer scale out when the source image size exceeds $ width = $ srcWidth; $ height = $ SrcHeight; if (! $ Is_preview) {// write the source image file_put_contents ($ thumbname, file_get_contents ($ image) in non-preview mode; // write the return array ('URL' => $ thumburl, 'Path' => $ thumbname);} else {// Thumbnail size $ width = (int) ($ srcWidth * $ scale); $ height = (int) ($ srcHeight * $ scale);} if ($ gen = 1) {$ width = $ maxWidth; $ height = $ maxHeight ;} // load the source image $ createFun = 'imagecreatefrom '. ($ type = 'jpg '? 'Jpeg ': $ type); if (! Function_exists ($ createFun) $ createFun = 'imagecreatefromjpeg '; $ srcImg = $ createFun ($ image); // Create a thumbnail if ($ type! = 'GIF' & function_exists ('imagecreatetruecolor') $ thumbImg = imagecreatetruecolor ($ width, $ height); else $ thumbImg = imagecreate ($ width, $ height ); $ x = 0; $ y = 0; if ($ gen = 1 & $ maxWidth> 0 & $ maxHeight> 0) {$ resize_ratio = $ maxWidth/$ maxHeight; $ src_ratio = $ srcWidth/$ srcHeight; if ($ src_ratio >=$ resize_ratio) {$ x = ($ srcWidth-($ resize_ratio * $ srcHeight)/2; $ width = ($ height * $ srcW Idth)/$ srcHeight;} else {$ y = ($ srcHeight-(1/$ resize_ratio) * $ srcWidth)/2; $ height = ($ width * $ srcHeight)/$ srcWidth;} // copy the image if (function_exists ("imagecopyresampled") imagecopyresampled ($ thumbImg, $ srcImg, 0, 0, $ x, $ y, $ width, $ height, $ srcWidth, $ srcHeight); else imagecopyresized ($ thumbImg, $ srcImg, 0, 0, $ x, $ y, $ width, $ height, $ srcWidth, $ srcHeight); if ('GIF' = $ type | 'PNG '==$ Type) {$ background_color = imagecolorallocate ($ thumbImg, 0,255, 0); // assign a green imagecolortransparent ($ thumbImg, $ background_color); // set the color to transparent, if this line is commented out, a green image will be output.} // you can set a line scan for the jpeg image if ('jpg '= $ type | 'jpeg' = $ type) imageinterlace ($ thumbImg, $ interlace); // generate an image imagejpeg ($ thumbImg, $ thumbname, 100); imagedestroy ($ thumbImg); imagedestroy ($ srcImg ); return array ('URL' => $ thumburl, 'path' => $ thumbname);} retur N false;} public function make_thumb ($ srcImg, $ srcWidth, $ srcHeight, $ type, $ maxWidth = 200, $ maxHeight = 50, $ gen = 0) {$ interlace = $ interlace? 1:0; if ($ maxWidth> 0 & $ maxHeight> 0) $ scale = min ($ maxWidth/$ srcWidth, $ maxHeight/$ srcHeight ); // calculate the scale of elseif ($ maxWidth = 0) $ scale = $ maxHeight/$ srcHeight; elseif ($ maxHeight = 0) $ scale = $ maxWidth/$ srcWidth; if ($ scale> = 1) {// no longer scale out when the source image size exceeds $ width = $ srcWidth; $ height = $ srcHeight ;} else {// Thumbnail size $ width = (int) ($ srcWidth * $ scale); $ height = (int) ($ srcHeight * $ scale );} if ($ gen = 1) {$ w Idth = $ maxWidth; $ height = $ maxHeight;} // Create a thumbnail if ($ type! = 'Gif '& function_exists ('imagecreatetruecolor') $ thumbImg = imagecreatetruecolor ($ width, $ height); else $ thumbImg = imagecreatetruecolor ($ width, height $ ); $ x = 0; $ y = 0; if ($ gen = 1 & $ maxWidth> 0 & $ maxHeight> 0) {$ resize_ratio = $ maxWidth/$ maxHeight; $ src_ratio = $ srcWidth/$ srcHeight; if ($ src_ratio >=$ resize_ratio) {$ x = ($ srcWidth-($ resize_ratio * $ srcHeight)/2; $ width = ($ heigh T * $ srcWidth)/$ srcHeight;} else {$ y = ($ srcHeight-(1/$ resize_ratio) * $ srcWidth)/2; $ height = ($ width * $ srcHeight)/$ srcWidth;} // copy the image if (function_exists ("imagecopyresampled") imagecopyresampled ($ thumbImg, $ srcImg, 0, 0, $ x, $ y, $ width, $ height, $ srcWidth, $ srcHeight); else imagecopyresized ($ thumbImg, $ srcImg, 0, 0, $ x, $ y, $ width, $ height, $ srcWidth, $ srcHeight); if ('GIF' = $ typ E | 'PNG '==$ type) {$ background_color = imagecolorallocate ($ thumbImg, 255,255,255); // assign a green imagecolortransparent ($ thumbImg, $ background_color ); // Set to transparent color, if this line is commented out, a green image will be output.} // you can set a line scan for the jpeg image if ('jpg '= $ type | 'jpeg' = $ type) imageinterlace ($ thumbImg, $ interlace); return $ thumbImg;} public function water ($ source, $ water, $ alpha = 80, $ position = "0 ") {// check whether the object exists if (! File_exists ($ source) |! File_exists ($ water) return false; // image information $ sInfo = es_imagecls: getImageInfo ($ source); $ wInfo = es_imagecls: getImageInfo ($ water ); // If the image is smaller than the watermark image, if ($ sInfo ["0"] <$ wInfo ["0"] | $ sInfo ['1'] <$ wInfo ['1']) return false; if (is_animated_gif ($ source) {require_once APP_ROOT_PATH. "system/utils/gif_encoder.php"; require_once APP_ROOT_PATH. "system/utils/gif_reader.php"; $ gif = new GIFReader (); $ gif-> Load ($ source); foreach ($ gif-> IMGS ['frames '] as $ k => $ img) {$ im = imagecreatefromstring ($ gif-> getgif ($ k); // add a watermark to im $ sImage = $ im; $ wCreateFun = "imagecreatefrom ". $ wInfo ['type']; if (! Function_exists ($ wCreateFun) $ wCreateFun = 'imagecreatefromjpeg '; $ wImage = $ wCreateFun ($ water); // sets the image blending mode imagealphablending ($ wImage, true ); switch (intval ($ position) {case 0: break; // upper left case 1: $ posY = 0; $ posX = 0; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // upper right case 2: $ posY = 0; $ posX = $ sInfo [0]-$ wInfo [0]; // Generate a hybrid image imagecopymerge ($ sImage, $ wI Mage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // Lower left case 3: $ posY = $ sInfo [1]-$ wInfo [1]; $ posX = 0; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // Lower right case 4: $ posY = $ sInfo [1]-$ wInfo [1]; $ posposx = $ sInfo [0]-$ wInfo [0]; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // center case 5: $ posY = $ sInfo [1]/2-$ wInfo [1]/2; $ posX = $ sInfo [0]/2-$ wInfo [0]/2; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha ); break;} // end im watermark ob_start (); imagegif ($ sImage); $ content = ob_get_contents (); ob_end_clean (); $ frames [] = $ content; $ framed [] = $ img ['framedelay'];} $ gif_maker = new GIFEncoder ($ frames, $ framed, 0, 2, 0, 0, 0, 0, "bin" // The binary url is the address); $ image_rs = $ Gif_maker-> GetAnimation (); // if no save file name is provided, the default value is the original image name @ unlink ($ source); // save the image file_put_contents ($ source, $ image_rs ); return true;} // create an image $ sCreateFun = "imagecreatefrom ". $ sInfo ['type']; if (! Function_exists ($ sCreateFun) $ sCreateFun = 'imagecreatefromjpeg '; $ sImage = $ sCreateFun ($ source); $ wCreateFun = "imagecreatefrom ". $ wInfo ['type']; if (! Function_exists ($ wCreateFun) $ wCreateFun = 'imagecreatefromjpeg '; $ wImage = $ wCreateFun ($ water); // sets the image blending mode imagealphablending ($ wImage, true ); switch (intval ($ position) {case 0: break; // upper left case 1: $ posY = 0; $ posX = 0; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // upper right case 2: $ posY = 0; $ posX = $ sInfo [0]-$ wInfo [0]; // Generate a hybrid image imagecopymerge ($ sImage, $ wI Mage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // Lower left case 3: $ posY = $ sInfo [1]-$ wInfo [1]; $ posX = 0; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // Lower right case 4: $ posY = $ sInfo [1]-$ wInfo [1]; $ posX = $ sInfo [0]-$ wInfo [0]; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha); break; // center case 5: $ posY = $ sInfo [1]/2-$ wInfo [1]/2; $ posX = $ sInfo [0]/2-$ wInfo [0]/2; // Generate a hybrid image imagecopymerge ($ sImage, $ wImage, $ posX, $ posY, 0, 0, $ wInfo [0], $ wInfo [1], $ alpha ); break;} // if no save file name is provided, the default value is the original image name @ unlink ($ source); // save the image imagejpeg ($ sImage, $ source, 100 ); imagedestroy ($ sImage) ;}} if (! Function_exists ('image _ type_to_extension ') {function image_type_to_extension ($ imagetype) {if (empty ($ imagetype) return false; switch ($ imagetype) {case IMAGETYPE_GIF: return '.gif '; case IMAGETYPE_JPEG: return '.jpeg'; case IMAGETYPE_PNG: return '.png '; case IMAGETYPE_SWF: return '.swf'; case IMAGETYPE_PSD: return '. psd '; case IMAGETYPE_BMP: return '.bmp'; case imagetype_ii _ii: return '. Tiff '; case imagetype_mm _mm: return '. tiff '; case IMAGETYPE_JPC: return '. jpc'; case IMAGETYPE_JP2: return '. jp2 '; case IMAGETYPE_JPX: return '. jpf '; case IMAGETYPE_JB2: return '. jb2 '; case IMAGETYPE_SWC: return '. swc '; case IMAGETYPE_IFF: return '. aiff '; case IMAGETYPE_WBMP: return '. wbmp '; case IMAGETYPE_XBM: return '. xbm '; default: return false ;}}?>

2. get_spec_img () calls the image class, saves images of different specifications and returns the image connection using the following method.

// Obtain the image address of the corresponding Specification // gen = 0: proportional scaling without cropping. if the height is 0, proportional width scaling is ensured. gen = 1: The length and width are guaranteed, crop function get_spec_image ($ img_path, $ width = 0, $ height = 0, $ gen = 0, $ is_preview = true) {if ($ width = 0) $ new_path = $ img_path; else {$ img_name = substr ($ img_path, 0,-4); $ img_ext = substr ($ img_path,-3); if ($ is_preview) $ new_path = $ img_name. "_". $ width. "x ". $ height. ". jpg "; else $ new_path = $ img_name. "o _". $ width. "x ". $ height. ". jpg "; if (! File_exists ($ new_path) {require_once "imagecls. php "; $ imagec = new imagecls (); $ thumb = $ imagec-> thumb ($ img_path, $ width, $ height, $ gen, true ,"", $ is_preview); if (app_conf ("PUBLIC_DOMAIN_ROOT ")! = '') {$ Paths = pathinfo ($ new_path); $ path = str_replace (". /"," ", $ paths ['dirname']); $ filename = $ paths ['basename']; $ pathwithoupublic = str_replace (" public /","", $ path); $ file_data = @ file_get_contents ($ path. $ file); $ img = @ imagecreatefromstring ($ file_data); if ($ img! = False) {$ save_path = "public/". $ path; if (! Is_dir ($ save_path) {@ mk_dir ($ save_path) ;}@ file_put_contents ($ save_path. $ name, $ file_data) ;}}} return $ new_path ;}

3. usage:

// Im: save the shop image as three types: Small Image: 48x48, medium 20x120, 00x200 $ small_url = get_spec_image ($ data ['image'], 120,120, 0); $ middle_url = get_spec_image ($ data ['image'], 0 ); $ big_url = get_spec_image ($ data ['image'], 200,200, 0 );

I hope this article will help you with php programming.

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.