【问题标题】:How can I generate a thumbnails from a directory of images using PHP?如何使用 PHP 从图像目录生成缩略图?
【发布时间】:2013-03-04 11:54:04
【问题描述】:

我有完整的高质量图像,并且直接在我的网站上。使用 PHP 我想从这个目录生成缩略图到另一个名为 'thumbs' 的目录。

我设法找到了一个代码来制作特定图像的缩略图,但是当我尝试为整个文件夹执行此操作时,它不起作用。

然后我从here 找到了另一个代码,这似乎是我正在寻找的(仅第一部分)。不幸的是,我不知道在哪里将源和目标插入到代码中。

    /* 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);
}

请问在哪里输入文件夹的来源和目的地?

【问题讨论】:

  • 上述问题之前没有在此表单上回答过。尽管建议的链接相似,但它们是不同的。

标签: php html


【解决方案1】:

输入目录将是$images_dir in get_files

您需要遍历此方法的结果并调用make_thumb,其中$dest 将是该特定文件的最终名称。

类似这样的东西(还没有测试过):

//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)
}

【讨论】:

  • 谢谢,但它对我不起作用。我在代码的顶部输入了它。
  • 我试过了。您在上面给我的 PHP 代码有效,但原始查询中的上述脚本无效。
猜你喜欢
  • 2016-03-18
  • 2016-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 2019-02-14
  • 2011-12-21
  • 2016-04-09
相关资源
最近更新 更多