Follow me on Twitter Facebook Flickr Subscribe Feeds
 

PHP: creare immagini thumbnail

This entry was posted on January 8th, 2009 and is filed under php.

Da sastgroup una comoda funzione per creare le thumbnail di immagini di grandi dimensioni. Comoda ad esempio per creare i back-office di siti che necessitano di gallery.

Il codice è visualizzabile dopo il link.


function create_img_gd($imgfile, $imgthumb, $newwidth) {
  if (function_exists("imagecreate")) {
    $imginfo = getimagesize($imgfile);

    switch($imginfo[2]) {
      case 1:
          $type = IMG_GIF;
          break;
      case 2:
          $type = IMG_JPG;
          break;
      case 3:
          $type = IMG_PNG;
          break;
      case 4:
          $type = IMG_WBMP;
          break;
      default:
          return $imgfile;
          break;
    }

    switch($type) {
      case IMG_GIF:
          if (!function_exists("imagecreatefromgif")) return $imgfile;
          $srcImage = imagecreatefromgif("$imgfile");
          break;
      case IMG_JPG:
          if (!function_exists("imagecreatefromjpeg")) return $imgfile;
          $srcImage = imagecreatefromjpeg($imgfile);
          break;
      case IMG_PNG:
          if(!function_exists("imagecreatefrompng")) return $imgfile;
          $srcImage = imagecreatefrompng("$imgfile");
          break;
      case IMG_WBMP:
          if (!function_exists("imagecreatefromwbmp")) return $imgfile;
          $srcImage = imagecreatefromwbmp("$imgfile");
          break;
      default:
          return $imgfile;
    }

    if ($srcImage){
      $srcWidth = $imginfo[0];
      $srcHeight = $imginfo[1];
      $ratioWidth = $srcWidth / $newwidth;
      $destWidth = $newwidth;
      $destHeight = $srcHeight / $ratioWidth;
      $destImage = imagecreatetruecolor($destWidth, $destHeight);
      imagealphablending($destImage, true);
      imagealphablending($srcImage, false);
      imagecopyresized($destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);

      switch($type) {
        case IMG_GIF:
            imagegif($destImage, "$imgthumb");
            break;
        case IMG_JPG:
            imagejpeg($destImage, "$imgthumb");
            break;
        case IMG_PNG:
            imagepng($destImage, "$imgthumb");
            break;
        case IMG_WBMP:
            imagewbmp($destImage, "$imgthumb");
            break;
      }

      imagedestroy($srcImage);
      imagedestroy($destImage);
      return $imgthumb;
    } else {return $imgfile;}
  } else {return $imgfile;}
}

Via | sastgroup

Like this post? Share It! :)
Navigation:
Related Posts:
Comments

Leave a Reply