创建图像缩略图,然后将其保存到数据库中

时间:2012-06-22 07:49:27

标签: php mysql

我正在创建图像的缩略图,然后将其保存到数据库中,但我不知道该怎么做。这是我的代码

 function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
 {
        $pathToImages = "../uploads/images/";
        // 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' ) 
          {

            $pathToThumbs = "../uploads/images/thumbs/";
        //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}" );
         $thumbimage =  $fname;
          }
        }
        // close the directory
closedir( $dir );

 }
 createThumbs("/uploads/documents","/uploads/images/thumbs/",100);

创建缩略图很好,但现在我不知道如何将其保存在db(缺乏技能)

2 个答案:

答案 0 :(得分:1)

为什么不将结果保存在文件中?

我认为你必须在数据库字段中选择文本类型,然后在那里保存图像的内容,

使用“Content-type:image / jpg”标题读取不同php文件中的数据。

例如:

$query = "SELECT image FROM youtablename WHERE id = 10";
$result = mysql_query($query) or die('Error, query failed');
$content=mysql_result($result,0,"image");
header("Content-type: image/jpg");
echo $content;

答案 1 :(得分:0)

您可以使用自动生成缩略图的Dropbox API。我认为在数据库中保存二进制文件是我们可以犯的最大错误。特别是对于性能和文件管理变得困难。

相关问题