使用 PHP 从图像文件夹创建缩略图

ste*_*ail 1 php mysql image-processing thumbnails

我有一个 jpegs 文件夹和一个 MySQL 数据库,我希望用来管理它们。数据库有一张表:'images',和 7 个字段:'imgID'、'imgTitle'、'imgURL'、'imgDate'、'imgClass'、'imgFamily' 和 'imgGender'。主键是“imgID”,索引键是“imgDate”。

我想要做的是创建一个 PHP 文件,该文件将遍历我的图像文件夹(所有 jpeg),并创建它们的缩略图,然后在我的网页上显示图像链接时可以使用这些缩略图。由于我将来会向文件夹添加更多图像,因此最好防止代码创建它已经创建缩略图的图像的双倍。

我遇到的所有文献都建议使用 gd 图像库来做到这一点,但我愿意接受建议。

由于我是 MySQL 和 PHP 的新手,我希望有人可以帮助我编写代码。我尝试过的一切都失败了。

图片所在目录相对于站点根目录为new_arrivals_img/,缩略图也应放置在相对于站点根目录的new_arrivals_img/thumbnails/中。

现在我正在构建站点,因此使用 MAMP 在本地托管它。我在确定图像的相对路径时遇到了一些问题。有没有办法将 new_arrivals_img/ 设置为根?

Cod*_*ian 5

据说 ImageMagick 在内存上更好,但我总是有 GD 可供我使用,它总是为我完成工作。确保在 php.ini 中分配足够的内存

然后使用这样的脚本:

<?php
function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
  // open the directory
  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {
      echo "Creating thumbnail for {$fname} <br />";

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
    }
  }
  // close the directory
  closedir( $dir );
}
// call createThumb function and pass to it as parameters the path 
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width. 
// We are assuming that the path will be a relative path working 
// both in the filesystem, and through the web for links
createThumbs("new_arrivals_img/","new_arrivals_img/thumbnails/",100);
?>
Run Code Online (Sandbox Code Playgroud)

http://www.webcheatsheet.com/php/create_thumbnail_images.php