2012-06-22 52 views
0

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

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); 

创建缩略图的是好的,但现在我不知道如何将它保存在数据库(缺乏技能)

+0

我建议你将图像保存在文件中,并只保留数据库中的URL。如果您需要保护您的图片免受公众影响,您可以使用.htaccess来实现 – Kyborek

回答

1

你为什么不保存在文件中的结果吗?

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

,并与“内容类型: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; 
0

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

相关问题