PHP saves pictures as picture class instances with different size pictures _php tips

Source: Internet
Author: User
Tags chmod imagejpeg transparent color save file trim

This article illustrates how PHP saves pictures as different sizes of picture classes. Share to everyone for your reference. Specifically as follows:

Picture 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;
  /** * 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 ($f ile, $dir = ' temp ') {if (!is_array ($file) | | | empty ($file) | |! $this->isuploadfile ($file [' tmp_name ']) | | Trim ($fil e[' 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_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; /** * Gets the file name extension * @return string/function Fileext ($file _name) {return addslashes strtolower (
  STRRCHR ($file _name, '. '), 1, 10));  /** * According to the extension to determine whether the file is an image * @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;  /** * Get 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 (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) {R Eturn $source && ($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) {i F (!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 fun
    Ction 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; The Public function thumb ($image, $maxWidth =200, $maxHeight =50, $gen = 0, $inTerlace=true, $filepath = ", $is _preview = 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 is written 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 ')) $thumbImg = Imagecreatetruecolor ($width, $height);
      else $thumbImg = Imagecreate ($width, $height);
      $x = 0;
      $y = 0; if ($gen = = 1 && $maxWidth > 0 && $maxHeight > 0) {$resize _ratio = $maxWidth/$maxHeigh
        T
        $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 ($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 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; The Public Function Make_thumb ($SRCIMG, $srcWidth, $srcHeight, $type, $maxWidth =200, $maxHeight =50, $gen = 0) {$interla Ce = $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 thumbnail if ($type!= ' gif ' && function_exists (' Imagecreatetruecolor ')) $THUMBIMG = Imagecreatet
      Ruecolor ($width, $height);
      else $thumbImg = Imagecreatetruecolor ($width, $height);
      $x = 0;
      $y = 0; if ($gen = = 1 && $maxWidth > 0 && $maxHeight > 0) {$resize _ratio = $maxWidth/$maxHeigh
        T
        $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 ($thumbImg, $srcImg, 0, 0, $x, $y, $w
      Idth, $height, $srcWidth, $srcHeight);
      else imagecopyresized ($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth, $srcHeight); if (' gif ' = = $type | | ' png ' = = $type) {$background _color = imagecolorallocate ($thumbImg, 255,255,255);//Assign a green IMAGECOLORTRANSP Arent ($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 ($source) | |!
    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 address of binary URL);
      $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 ($ima
    Getype)) 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 in the following way and returns a picture connection

Get the corresponding specifications of the picture address//gen=0: To maintain proportional scaling, do not cut, such as height of 0, then ensure width scaling gen=1: To ensure long width, trim 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. 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);

I hope this article will help you with your PHP program design.

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.