php - Generating Thumbnail, Copying It To Directory & Saving it To Database -


i wanting use pre-authored script generate thumbnail of image, , need modify needs, having copy saved file directory, , saving filename mysql database. unsure in script, can't determine when actual file output script(lack of skill).

any appreciated, lea.

the code add script follows:

if( $new_height == "50" && $new_width == "50" ) {  // write code here query, , copy file  } 

the pre-authored script:

/*     timthumb script created tim mcdaniels , darren hoyt tweaks ben gillbanks     http://code.google.com/p/timthumb/      mit license: http://www.opensource.org/licenses/mit-license.php      paramters     ---------     w: width     h: height     zc: zoom crop (0 or 1)     q: quality (default 75 , max 100)      html example: <img src="/scripts/timthumb.php?src=/images/whatever.jpg&w=150&h=200&zc=1" alt="" /> */  /* $sizelimits = array(     "100x100",     "150x150", ); */  define ('cache_size', 250);     // number of files store before clearing cache define ('cache_clear', 5);      // maximum number of files delete on each cache clear define ('version', '1.09');     // version number (to force cache refresh  $imagefilters = array(     "1" => array(img_filter_negate, 0),     "2" => array(img_filter_grayscale, 0),     "3" => array(img_filter_brightness, 1),     "4" => array(img_filter_contrast, 1),     "5" => array(img_filter_colorize, 4),     "6" => array(img_filter_edgedetect, 0),     "7" => array(img_filter_emboss, 0),     "8" => array(img_filter_gaussian_blur, 0),     "9" => array(img_filter_selective_blur, 0),     "10" => array(img_filter_mean_removal, 0),     "11" => array(img_filter_smooth, 0), );  // sort out image source $src = get_request("src", ""); if($src == "" || strlen($src) <= 3) {     displayerror("no image specified"); }  // clean params before use $src = cleansource($src); // last modified time (for caching) $lastmodified = filemtime($src);  // properties $new_width      = preg_replace("/[^0-9]+/", "", get_request("w", 0)); $new_height     = preg_replace("/[^0-9]+/", "", get_request("h", 0)); $zoom_crop      = preg_replace("/[^0-9]+/", "", get_request("zc", 1)); $quality        = preg_replace("/[^0-9]+/", "", get_request("q", 80)); $filters        = get_request("f", "");  if ($new_width == 0 && $new_height == 0) {     $new_width = 100;     $new_height = 100; }  // set path cache directory (default ./cache) // can changed different location $cache_dir = './cache';  // mime type of src $mime_type = mime_type($src);  // check see if image in cache check_cache( $cache_dir, $mime_type );  // if not in cache clear space , generate new file cleancache();  ini_set('memory_limit', "30m");  // make sure src gif/jpg/png if(!valid_src_mime_type($mime_type)) {     displayerror("invalid src mime type: " .$mime_type); }  // check see if gd function exist if(!function_exists('imagecreatetruecolor')) {     displayerror("gd library error: imagecreatetruecolor not exist"); }  if(strlen($src) && file_exists($src)) {      // open existing image     $image = open_image($mime_type, $src);     if($image === false) {         displayerror('unable open image : ' . $src);     }      // original width , height     $width = imagesx($image);     $height = imagesy($image);      // don't allow new width or height greater original     if( $new_width > $width ) {         $new_width = $width;     }     if( $new_height > $height ) {         $new_height = $height;     }      // generate new w/h if not provided     if( $new_width && !$new_height ) {          $new_height = $height * ( $new_width / $width );      } elseif($new_height && !$new_width) {          $new_width = $width * ( $new_height / $height );      } elseif(!$new_width && !$new_height) {          $new_width = $width;         $new_height = $height;      }      // create new true color image     $canvas = imagecreatetruecolor( $new_width, $new_height );     imagealphablending($canvas, false);     // create new transparent color image     $color = imagecolorallocatealpha($canvas, 0, 0, 0, 127);     // fill background of new image allocated color.     imagefill($canvas, 0, 0, $color);     // restore transparency blending     imagesavealpha($canvas, true);      if( $zoom_crop ) {          $src_x = $src_y = 0;         $src_w = $width;         $src_h = $height;          $cmp_x = $width  / $new_width;         $cmp_y = $height / $new_height;          // calculate x or y coordinate , width or height of source          if ( $cmp_x > $cmp_y ) {              $src_w = round( ( $width / $cmp_x * $cmp_y ) );             $src_x = round( ( $width - ( $width / $cmp_x * $cmp_y ) ) / 2 );          } elseif ( $cmp_y > $cmp_x ) {              $src_h = round( ( $height / $cmp_y * $cmp_x ) );             $src_y = round( ( $height - ( $height / $cmp_y * $cmp_x ) ) / 2 );          }          imagecopyresampled( $canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h );      } else {          // copy , resize part of image resampling         imagecopyresampled( $canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );      }      if ($filters != "") {         // apply filters image         $filterlist = explode("|", $filters);         foreach($filterlist $fl) {             $filtersettings = explode(",", $fl);             if(isset($imagefilters[$filtersettings[0]])) {                  for($i = 0; $i < 4; $i ++) {                     if(!isset($filtersettings[$i])) {                         $filtersettings[$i] = null;                     }                 }                  switch($imagefilters[$filtersettings[0]][1]) {                      case 1:                          imagefilter($canvas, $imagefilters[$filtersettings[0]][0], $filtersettings[1]);                         break;                      case 2:                          imagefilter($canvas, $imagefilters[$filtersettings[0]][0], $filtersettings[1], $filtersettings[2]);                         break;                      case 3:                          imagefilter($canvas, $imagefilters[$filtersettings[0]][0], $filtersettings[1], $filtersettings[2], $filtersettings[3]);                         break;                      default:                          imagefilter($canvas, $imagefilters[$filtersettings[0]][0]);                         break;                  }             }         }     }      // output image browser based on mime type     show_image($mime_type, $canvas, $cache_dir);      // remove image memory     imagedestroy($canvas);  } else {      if(strlen($src)) {         displayerror("image " . $src . " not found");     } else {         displayerror("no source specified");     }  }  /**  *   */ function show_image($mime_type, $image_resized, $cache_dir) {      global $quality;      // check see if can write cache directory     $is_writable = 0;     $cache_file_name = $cache_dir . '/' . get_cache_file();      if(touch($cache_file_name)) {          // give 666 permissions developer          // can overwrite web server user         chmod($cache_file_name, 0666);         $is_writable = 1;      } else {          $cache_file_name = null;         header('content-type: ' . $mime_type);      }      $quality = floor($quality * 0.09);      imagepng($image_resized, $cache_file_name, $quality);      if($is_writable) {         show_cache_file($cache_dir, $mime_type);      }      imagedestroy($image_resized);      displayerror("error showing image");  }  /**  *   */ function get_request( $property, $default = 0 ) {      if( isset($_request[$property]) ) {          return $_request[$property];      } else {          return $default;      }  }  /**  *   */ function open_image($mime_type, $src) {      if(stristr($mime_type, 'gif')) {          $image = imagecreatefromgif($src);      } elseif(stristr($mime_type, 'jpeg')) {          @ini_set('gd.jpeg_ignore_warning', 1);         $image = imagecreatefromjpeg($src);      } elseif( stristr($mime_type, 'png')) {          $image = imagecreatefrompng($src);      }      return $image;  }  /**  * clean out old files cache  * can change number of files store , delete per loop in defines @ top of code  */ function cleancache() {      $files = glob("cache/*", glob_brace);      $yesterday = time() - (24 * 60 * 60);      if (count($files) > 0) {          usort($files, "filemtime_compare");         $i = 0;          if (count($files) > cache_size) {              foreach ($files $file) {                  $i ++;                  if ($i >= cache_clear) {                     return;                 }                  if (filemtime($file) > $yesterday) {                     return;                 }                  unlink($file);              }          }      }  }  /**  * compare file time of 2 files  */ function filemtime_compare($a, $b) {      return filemtime($a) - filemtime($b);  }  /**  * determine file mime type  */ function mime_type($file) {      if (stristr(php_os, 'win')) {          $os = 'win';     } else {          $os = php_os;     }      $mime_type = '';      if (function_exists('mime_content_type')) {         $mime_type = mime_content_type($file);     }      // use pecl fileinfo determine mime type     if (!valid_src_mime_type($mime_type)) {         if (function_exists('finfo_open')) {             $finfo = finfo_open(fileinfo_mime);             $mime_type = finfo_file($finfo, $file);             finfo_close($finfo);         }     }      // try determine mime type using unix file command     // should not executed on windows     if (!valid_src_mime_type($mime_type) && $os != "win") {         if (preg_match("/freebsd|linux/", $os)) {             $mime_type = trim(@shell_exec('file -bi "' . $file . '"'));         }     }      // use file's extension determine mime type     if (!valid_src_mime_type($mime_type)) {          // set defaults         $mime_type = 'image/png';         // file details         $filedetails = pathinfo($file);         $ext = strtolower($filedetails["extension"]);         // mime types         $types = array(             'jpg'  => 'image/jpeg',             'jpeg' => 'image/jpeg',             'png'  => 'image/png',             'gif'  => 'image/gif'         );          if (strlen($ext) && strlen($types[$ext])) {             $mime_type = $types[$ext];         }      }      return $mime_type;  }  /**  *   */ function valid_src_mime_type($mime_type) {      if (preg_match("/jpg|jpeg|gif|png/i", $mime_type)) {         return true;     }      return false;  }  /**  *   */ function check_cache($cache_dir, $mime_type) {      // make sure cache dir exists     if (!file_exists($cache_dir)) {         // give 777 permissions developer can overwrite         // files created web server user         mkdir($cache_dir);         chmod($cache_dir, 0777);     }      show_cache_file($cache_dir, $mime_type);  }  /**  *   */ function show_cache_file($cache_dir) {      $cache_file = $cache_dir . '/' . get_cache_file();      if (file_exists($cache_file)) {          $gmdate_mod = gmdate("d, d m y h:i:s", filemtime($cache_file));          if(! strstr($gmdate_mod, "gmt")) {             $gmdate_mod .= " gmt";         }          if (isset($_server["http_if_modified_since"])) {              // check updates             $if_modified_since = preg_replace("/;.*$/", "", $_server["http_if_modified_since"]);              if ($if_modified_since == $gmdate_mod) {                 header("http/1.1 304 not modified");                 exit;             }          }          $filesize = filesize($cache_file);          // send headers display image         header("content-type: image/png");         header("accept-ranges: bytes");         header("last-modified: " . $gmdate_mod);         header("content-length: " . $filesize);         header("cache-control: max-age=9999, must-revalidate");         header("expires: " . $gmdate_mod);          readfile($cache_file);          exit;      }  }  /**  *   */ function get_cache_file() {      global $lastmodified;     static $cache_file;      if(!$cache_file) {         $cachename = $_server['query_string'] . version . $lastmodified;         $cache_file = md5($cachename) . '.png';     }      return $cache_file;  }  /**  * check if url valid or not  */ function valid_extension ($ext) {      if (preg_match("/jpg|jpeg|png|gif/i", $ext)) {         return true;     } else {         return false;     }  }  /**  * tidy image source url  */ function cleansource($src) {      // remove slash start of string     if(strpos($src, "/") == 0) {         $src = substr($src, -(strlen($src) - 1));     }      // remove http/ https/ ftp     $src = preg_replace("/^((ht|f)tp(s|):\/\/)/i", "", $src);     // remove domain name source url     $host = $_server["http_host"];     $src = str_replace($host, "", $src);     $host = str_replace("www.", "", $host);     $src = str_replace($host, "", $src);      // don't allow users ability use '../'      // in order gain access files below document root      // src should specified relative document root like:     // src=images/img.jpg or src=/images/img.jpg     // not like:     // src=../images/img.jpg     $src = preg_replace("/\.\.+\//", "", $src);      // path image on file system     $src = get_document_root($src) . '/' . $src;          return $src;  }  /**  *   */ function get_document_root ($src) {      // check unix servers     if(@file_exists($_server['document_root'] . '/' . $src)) {         return $_server['document_root'];     }      // check script filename (to directories timthumb location)     $parts = array_diff(explode('/', $_server['script_filename']), explode('/', $_server['document_root']));     $path = $_server['document_root'] . '/';     foreach ($parts $part) {         $path .= $part . '/';         if (file_exists($path . $src)) {             return $path;         }     }         // relative paths below useful if timthumb moved outside of document root     // if installed in wordpress themes mimbo pro:     // /wp-content/themes/mimbopro/scripts/timthumb.php     $paths = array(         ".",         "..",         "../..",         "../../..",         "../../../..",         "../../../../.."     );      foreach($paths $path) {         if(@file_exists($path . '/' . $src)) {             return $path;         }     }      // special check microsoft servers     if(!isset($_server['document_root'])) {         $path = str_replace("/", "\\", $_server['orig_path_info']);         $path = str_replace($path, "", $_server['script_filename']);          if( @file_exists( $path . '/' . $src ) ) {             return $path;           }     }         displayerror('file not found ' . $src);  }  /**  * generic error message  */ function displayerror($errorstring = '') {      header('http/1.1 400 bad request');     die($errorstring);  } 

i'm using uploadify upload images.

by default, images uploaded, stored on web servers temp dir (which defined in php init file).

then use resize_save_jpeg( $sourcefile, $targetfile, 480, 480, 80); resize image , save in new directory.

$sourcefileis path+filename of image in temp directory, , $targetfile path+filename new thumbnail image.

the 80 jpeg quality. thumbnails, think 60 more enough.

here resize code. don't remember got from:

function resize_save_jpeg( $sourcefile, $targetfile, $target_image_width, $target_image_height, $quality ) {     list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $sourcefile );     switch ( $source_image_type )     {         case imagetype_gif:         $source_gd_image = imagecreatefromgif( $sourcefile );         break;         case imagetype_jpeg:         $source_gd_image = imagecreatefromjpeg( $sourcefile );         break;         case imagetype_png:         $source_gd_image = imagecreatefrompng( $sourcefile );         break;     }      if ( $source_gd_image === false )     {         return false;     }      $source_aspect_ratio = $source_image_width / $source_image_height;     $target_aspect_ratio = $target_image_width / $target_image_height;      if ( $source_image_width <= $target_image_width && $source_image_height <= $target_image_height ) {         $target_image_width = $source_image_width;         $target_image_height = $source_image_height;     }     elseif ( $target_aspect_ratio > $source_aspect_ratio ) {         $target_image_width = ( int ) ( $target_image_height * $source_aspect_ratio );     }     else {         $target_image_height = ( int ) ( $target_image_width / $source_aspect_ratio );     }      $target_gd_image = imagecreatetruecolor( $target_image_width, $target_image_height );     imagecopyresampled( $target_gd_image, $source_gd_image, 0, 0, 0, 0, $target_image_width, $target_image_height, $source_image_width, $source_image_height );     imagejpeg( $target_gd_image, $targetfile, $quality );     imagedestroy( $source_gd_image );     imagedestroy( $target_gd_image );     return true; } 

edit
ups - missed database part.

i never saved image database. create reference image. reference, mean pathname image.

to ensure have unique image names, can create md5 server time, , use filename. in database, store path or name (or both).

so after image saved, add path/filname db.

edit 2

the $_files attribute global variable contains array of values (see link).
use + getimagesize retrieve data want:

$sourcefile   = $_files[ 'filedata' ][ 'tmp_name' ]; $fileinfo   = getimagesize($_files[ 'filedata' ][ 'tmp_name' ]); $filename   = md5(date("f d, y h:i:s", time())); $extension  = getexts($fileinfo[2]);         $targetfile = "my/static/path".$filename.$extension;  // file extension file binary. function getexts($filetype)  {     switch ($filetype) {         case "1": return "gif"; break;         case "2": return "jpg"; break;         case "3": return "png"; break;         return "0"; break;             } } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -