duanbi8529 2013-03-04 03:35
浏览 26

如何使用PHP从图像目录生成缩略图?

I have full high quality images and in a specific directly on my website. Using PHP I would like to generate thumbnails from this directory to another directory called 'thumbs'.

I managed to find a code to do a thumbnail of a particular image, but when I tried to do it for a whole folder it didn't work.

Then I found another code from here which seems to be what I'm looking for (only the first part). Unfortunately, I do not know where to insert the source and destination into the code.

    /* function:  generates thumbnail */
function make_thumb($src,$dest,$desired_width) {
  /* read the source image */
  $source_image = imagecreatefromjpeg($src);
  $width = imagesx($source_image);
  $height = imagesy($source_image);
  /* find the "desired height" of this thumbnail, relative to the desired width  */
  $desired_height = floor($height*($desired_width/$width));
  /* create a new, "virtual" image */
  $virtual_image = imagecreatetruecolor($desired_width,$desired_height);
  /* copy source image at a resized size */
  imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
  /* create the physical thumbnail image to its destination */
  imagejpeg($virtual_image,$dest);
}

/* function:  returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
  $files = array();
  if($handle = opendir($images_dir)) {
    while(false !== ($file = readdir($handle))) {
      $extension = strtolower(get_file_extension($file));
      if($extension && in_array($extension,$exts)) {
        $files[] = $file;
      }
    }
    closedir($handle);
  }
  return $files;
}

/* function:  returns a file's extension */
function get_file_extension($file_name) {
  return substr(strrchr($file_name,'.'),1);
}

Where do I input my source and destination of the folders please?

  • 写回答

1条回答 默认 最新

  • dqbhdsec59405 2013-03-04 03:54
    关注

    The input directory would be $images_dir in get_files.

    You'll need to loop over the results of this method and call make_thumb where $dest will be the final name of that particular file.

    Something like this (haven't tested this):

    //Set up variables we need
    $image_directory = "/some/directory/with/images/";
    $thumbs_directory = "/some/directory/for/thumbs/";
    $desired_width = 100;
    
    //Get the name of files in $image_directory
    foreach(get_files($image_directory) as $image){
        //Call make thumb with the given image location and put it into the thumbs directory.
        make_thumb($image_directory . $image, $thumbs_directory . $image, $desired_width)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路