如何为数据库中的所有图像创建缩略图

时间:2014-09-13 08:58:52

标签: php sql mysqli jpeg thumbnails

我想我之前没有考虑到这一点,但现在我意识到我需要显示小图片,以便用户可以选择然后查看更大的图像,我试图更快地提出请求。

所以现在这样做了,但我不知道如何将我的目录常量放在while语句中,因为它被多次调用并返回“已经定义的常量”。

我想我必须以某种方式只将路径放在while循环中,但我不知道如何。

这是完整的代码。

好吧,如果有更简单的方法可以做到这一点,我会喜欢它。

<?php
require_once '../php/db_conxi.php';
$pictures = mysqli_query($con, "SELECT * FROM imgs WHERE thumb = '' limit 20") or die(mysqli_error($con));
    while($row_pictures = mysqli_fetch_array($pictures)){

$uid = $row_pictures['uid'];
define("UPLOAD_DIR", "../user/".$uid."/thumbs/");
if (!file_exists(UPLOAD_DIR)){
    mkdir(UPLOAD_DIR, 0777, true);
    }       

      $filename_thumb = $row_pictures['img'];
       $photoid = $row_pictures['photoid'];
$width_thumb = 250;
$height_thumb = 250;
list($width_orig_thumb, $height_orig_thumb) = getimagesize($filename_thumb);
$ratio_orig_thumb = $width_orig_thumb/$height_orig_thumb;
if ($width_thumb/$height_thumb > $ratio_orig_thumb) {
   $width_thumb = $height_thumb*$ratio_orig_thumb;
} else {
   $height_thumb = $width_thumb/$ratio_orig_thumb;
}
$image_p_thumb = imagecreatetruecolor($width_thumb, $height_thumb);
    $info_thumb = getimagesize($filename_thumb);
    if ($info_thumb['mime'] == 'image/jpeg') $image_thumb = imagecreatefromjpeg($filename_thumb);
    elseif ($info_thumb['mime'] == 'image/gif') $image_thumb = imagecreatefromgif($filename_thumb);
    elseif ($info_thumb['mime'] == 'image/png') $image_thumb = imagecreatefrompng($filename_thumb);

imagecopyresampled($image_p_thumb, $image_thumb, 0, 0, 0, 0, $width_thumb, $height_thumb, $width_orig_thumb, $height_orig_thumb);
$thumb = ''.UPLOAD_DIR.'/hazard_thumb_'.time().time().time().rand().rand().rand().rand().'.jpg';
$thumb_convert = imagejpeg($image_p_thumb, $thumb, 90);
//////////////Store thumb///////////
    $query = mysqli_query($con, "UPDATE imgs SET thumb = '$thumb' WHERE photoid = '$photoid'") or die (mysqli_error($con));

    if ($query){
        echo 'Done with all thumbs';
        } else {
            'There was an error here';
            }
      }

?> 

0 个答案:

没有答案