PHP saves pictures as different sizes of pictures

Source: Internet
Author: User
Tags bool chmod error code file upload imagejpeg transparent color save file trim

 1. Picture processing class. imagecls.php

<?php/** Image Processing class */class Imagecls {/** * file information */var $file = array ();
	/** * Save Directory/var $dir = ';
	/** * ERROR code * * var $error _code = 0;

	/** * File Upload max kb/var $max _size =-1; function Es_imagecls () {} private Function Checksize ($size) {return! $size > $this->max_size) | |
    ( -1 = = $this->max_size); /** * Processing uploaded files * @param array $file uploaded files * @param string $dir saved directory * @return bool/function init ($fil E, $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 [' ext ']
= $this->fileext ($file [' name ']);
$file [' name '] = Htmlspecialchars ($file [' name '], ent_quotes); $file [' is_image '] = $this->isimageext ($file [' ext ']]);
$file [' file_dir '] = $this->gettargetdir ($dir);
$file [' prefix '] = MD5 (Microtime (TRUE)). Rand (10,99); $file [' target '] = './public/'. $file [' File_dir ']. ' /'. $file [' prefix '].  JPG '; Relative $file [' local_target '] = App_root_path. public/". $file [' File_dir ']. ' /'. $file [' prefix '].

			JPG '//physical $this->file = & $file;
			$this->error_code = 0;
		return true; }/** * Save file * @return bool/function Save () {if (Empty ($this->file) | | empty ($this->file[' Tmp_nam
		E ']) $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; /** * Gets the file name extension * @return string/function Fileext ($file _name) {return addslashes strtolower (substr
	($file _name, '. '), 1, 10)); /** * Based on the extension to determine whether the file is an image * @param string $ext extension * @return bool/function Isimageext ($ext) {static $img _ex
		t = array (' jpg ', ' jpeg ', ' PNG ', ' BMP ', ' gif ', ' giff '); Return In_array ($ext, $img _ext)?
	1:0; /** * Get image information * @param string $target file path * @return Mixed/function Getimageinfo ($target) {$ext = Es_im
		Agecls::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 (1,2,3,6,13)) return false;
			$image _info[' type '] = Strtolower (substr (image_type_to_extension ($image _info[2)), 1);
		return $image _info;
	else return false; /** * Obtain whether the upload file is allowed * @param string $source file path * @return bool/function Isuploadfile ($source) {return $s Ource && ($source!= ' none ') && is_uploaded_file ($source) | | is_uploaded_file (Str_replace ("",
	", $source)));	      
        /** * Gets the saved path * @param string $dir The specified save 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 File * @param string $source 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)) $s
		Ucceed = true; ElseIf (@is_readable ($source) && (@ $fp _s = fopen ($source, ' RB ')) && (@ $fp _t = fopen ($t
				Arget, ' 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; The Public function thumb ($image, $maxWidth =200, $maxHeight =50, $gen = 0, $interlace =true, $filepath = ', $is _previe

        W = true) {$info = Es_imagecls::getimageinfo ($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);
			Compute the scaling ratio 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 ']. '
                                     /'. $basefilename. ' _ '. $maxWidth. ' x '. $maxHeight '.
				JPG '; else $thumbname = $paths [' dirname ']. '
                                     /'. $basefilename. ' O_ '. $maxWidth. ' x '. $maxHeight.
JPG ';			else $thumbname = $filepath;
				
            $thumburl = Str_replace (App_root_path, './', $thumbname);
                if ($scale >= 1) {//More than the original size is no longer abbreviated $width = $srcWidth;         
                $height = $srcHeight; if (! $is _preview) {//non-preview mode writes to the original File_put_contents ($thumbname, File_    Get_contents ($image));
                Write the return array (' URL ' => $thumburl, ' path ' => $thumbname) with the original artwork;
                } else {//thumbnail size $width = (int) ($srcWidth * $scale);
            $height = (int) ($srcHeight * $scale);
				} if ($gen = = 1) {$width = $maxWidth;
			$height = $maxHeight; //Load Original $createFun = ' Imagecreatefrom '. ($type = = ' jpg '?
			JPEG ': $type);

            if (!function_exists ($createFun)) $createFun = ' imagecreatefromjpeg ';
$SRCIMG = $createFun ($image);
            Create thumbnails if ($type!= ' gif ' && function_exists (' Imagecreatetruecolor ')) $thum
            bimg = 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 * $srcWidth)/$srcHeight;
				else {$y = ($srcHeight-((1/$resize _ratio) * $srcWidth))/2;
				$height = ($width * $srcHeight)/$srcWidth; }///Copy Picture if (Function_exists ("imagecopyresampled")) imagecopyresampled ($thum
            Bimg, $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 to Transparent color, if you comment out the line then output green figure}//Set interlaced scan for JPEG if (' jpg ' = $type | |

            ' jpeg ' = = $type) imageinterlace ($THUMBIMG, $interlace);
            Generate Picture imagejpeg ($THUMBIMG, $thumbname, 100);
            Imagedestroy ($THUMBIMG);

			Imagedestroy ($SRCIMG);
         Return array (' URL ' => $thumburl, ' path ' => $thumbname);
    return 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);    Compute the scaling ratio elseif ($maxWidth = 0) $scale = $maxHeight/$srcHeight;

            ElseIf ($maxHeight = = 0) $scale = $maxWidth/$srcWidth;
                if ($scale >= 1) {//More than the original size is no longer abbreviated $width = $srcWidth;
            $height = $srcHeight;
                else {//thumbnail size $width = (int) ($srcWidth * $scale);
            $height = (int) ($srcHeight * $scale);
				} if ($gen = = 1) {$width = $maxWidth;
			$height = $maxHeight; //Create thumbnails if ($type!= ' gif ' && function_exists (' Imagecreatetruecolor ')) $t
            humbimg = 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 = ($height * $srcWidth)/$srcHeight;
				else {$y = ($srcHeight-((1/$resize _ratio) * $srcWidth))/2;
				$height = ($width * $srcHeight)/$srcWidth; }///Copy Picture if (Function_exists ("imagecopyresampled")) imagecopyresampled ($thum
            Bimg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth, $srcHeight); else imagecopyresized ($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth, $SRC
            Height); if (' gif ' = = $type | |  
                ' png ' = = $type) {$background _color = imagecolorallocate ($thumbImg, 255,255,255); 
              Assign a green imagecolortransparent ($THUMBIMG, $background _color); Set to Transparent color, if you comment out the line then output green figure}//Set interlaced scan for JPEG if (' jpg ' = $type | |

   ' jpeg ' = = $type) imageinterlace ($THUMBIMG, $interlace);        return $THUMBIMG; The Public function water ($source, $water, $alpha =80, $position = "0") {//check that the file exists if!file_exists ($so Urce) | |!

        File_exists ($water)) return false;
        Picture information $sInfo = Es_imagecls::getimageinfo ($source);

        $wInfo = Es_imagecls::getimageinfo ($water);


            
        If the picture is less than the watermark picture, do not generate the picture 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 watermark to im $sImage = $im;
				$wCreateFun = "Imagecreatefrom". $wInfo [' type '];
		       if (!function_exists ($wCreateFun)) $wCreateFun = ' imagecreatefromjpeg '; $wImage = $wCreateFun ($water);		
		        Sets the blending mode imagealphablending ($wImage, true) of the image;
		        	Switch (intval ($position)) {case 0:break;
				        Upper left Case 1: $posY = 0;
				        $posX = 0;
		        		Generate mixed 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 mixed Image Imagecopymerge ($sImage, $wImage, $posX, $posY, 0, 0, $wInfo [0], $wInfo [1], $alpha);
		        	Break
				        Left case 3: $posY = $sInfo [1]-$wInfo [1];
				        $posX = 0;
		        		Generate mixed Image Imagecopymerge ($sImage, $wImage, $posX, $posY, 0, 0, $wInfo [0], $wInfo [1], $alpha);
		        	Break
				        Right Case 4: $posY = $sInfo [1]-$wInfo [1];
				        $posX = $sInfo [0]-$wInfo [0]; Generate mixed 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 mixed Image Imagecopymerge ($sImage, $wImage, $posX, $posY, 0, 0, $wInfo [0], $wInfo [1], $alpha);
		        Break
				//end im plus 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, "bin"//bin is the binary URL for the address);
			
			$image _rs = $gif _maker->getanimation ();
	        If no save file name is given, the default is the original image name @unlink ($source);
	        Save Image File_put_contents ($source, $image _rs);
        return true;
		//Create 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 blending mode imagealphablending ($wImage, true) of the image;
        	Switch (intval ($position)) {case 0:break;
		        Upper left Case 1: $posY = 0;
		        $posX = 0;
        		Generate mixed 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 mixed Image Imagecopymerge ($sImage, $wImage, $posX, $posY, 0, 0, $wInfo [0], $wInfo [1], $alpha);
        	Break
		        Left case 3: $posY = $sInfo [1]-$wInfo [1];
		        $posX = 0;
        		Generate mixed Image Imagecopymerge ($sImage, $wImage, $posX, $posY, 0, 0, $wInfo [0], $wInfo [1], $alpha);
        	Break Right Case 4: $posY = $sInfo [1]-$wInfo [1];
		        $posX = $sInfo [0]-$wInfo [0];
        		Generate mixed 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 mixed Image Imagecopymerge ($sImage, $wImage, $posX, $posY, 0, 0, $wInfo [0], $wInfo [1], $alpha);
        Break
        //If no save file name is given, default is the original image name @unlink ($source);
        Save Image imagejpeg ($sImage, $source, 100);
    Imagedestroy ($sImage); } if (!function_exists (' image_type_to_extension ')) {function image_type_to_extension ($imagetype) {if Empty ($imaget

		ype)) 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_tiff_ii:return '. TIFF ';
			Case Imagetype_tiff_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 picture class, and then saves the picture with a different specification and returns a picture connection in the following way

3. How to use:

Im: Store pictures are stored in 3 kinds of specifications: small figure: 48x48, 120x120, large figure 200x200
			$small _url=get_spec_image ($data [' Image '],48,48,0);
			$<span id= "Result_box" class= "Short_text" lang= "en" >
                  <span>middle_url</span></span>= Get_spec_image ($data [' Image '],120,120,0);
			$big _url=get_spec_image ($data [' Image '],200,200,0);

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.