上传,调整大小和保存使用PHP(或生成缩略图)


Upload , Resize and Save using PHP (or generating thumbnails)

我正在做一个网站,让用户能够跟踪他们最喜欢的乐队。该网站的功能之一是允许用户上传他们去过的任何演出的照片,然后将照片保存到一个文件中,图像位置存储在数据库中。

我的问题是我需要能够在保存时调整图像的大小,因为当有许多图片时,页面需要很长时间才能加载。

我知道这里有很多这样的问题,但我只是不确定如何修改我必须这样做的代码。

这是最好的方法还是我应该使用缩略图?由于图像将显示在一个图库中,如果有很多,那么页面将加载较慢

我的php知识有限,所以任何帮助都是感激的

这是我现在的代码:

 <?php
  ///UPLOAD IMAGES
 $sql = "SELECT * FROM photouploads WHERE BandID ='$bandid'";
 $result = mysql_query($sql,$connect)or die ($error1);
 $row = mysql_num_rows($result);
     $userid=$_SESSION['userid'];
 if (isset($_POST['submit']))
     {
         $name = $bandid."(".++$row.").jpg";
         $tmp_name=$_FILES['photo']['tmp_name'];
         if ($name)
         {
             //start upload
             $location="Photouploads/".$name;
             if (move_uploaded_file($tmp_name,$location))
                  {
                   mysql_query("INSERT INTO photouploads (BandID,UserID,ImageLocation)
                   VALUES ('$bandid', '$userid', '$location')") ;
                  }
         }
else
;
}

和我的形式:

        <input type='file' name='photo' id='photo'> 
        <input type='submit' class='submitLink' name='submit' id='submit'value='upload'>
 </form>";
?>

这是我过去使用过的一个非常基本的PHP图像大小调整类。您需要安装并启用PHP GD2模块才能使其工作。

用法:

$resized = ImageResizer::resizeExistingImage($_FILES['photo']['tmp_name'],
                                                                null,
                                                                500,
                                                                500,
                                                                100);
if (!$resized){
    throw new Exception('Could not resize image');
}
echo '<pre>';
print_r($resized);
echo '</pre>';

类:

class ImageResizer
{
    const RESULT_RESIZE_NOT_REQUIRED = 'resize_not_required';
    const RESULT_RESIZE_SUCCESSFUL = 'resize_successful';
    private static $_filePath = null;
    private static $_newPath = null;
    private static $_maxwidth = null;
    private static $_maxheight = null;
    private static $_quality = null;
    private static $_newWidth = null;
    private static $_newHeight = null;
    private static $_actualWidth = null;
    private static $_actualHeight = null;
    /**
     * Takes an image (from a file path) and resizes it. The newly resized image
     * can then either be created in a different location, therefore maintainig 
     * the original file. Or can be created in the original location, therefore
     * overwriting the original file.
     * 
     *
     * @static 
     * @access public
     * @param string    $filePath   The file path of the image to resize
     * @param string    $newPath    The file path where the resized image will 
     *                              be created. Null to overwrite original.
     * @param integer   $maxwidth   The maximum height of the resized image
     * @param integer   $maxheight  The maximum width of the resized image
     * @param integer   $quality    The quality of the image 
     */
    public static function resizeExistingImage($filePath, 
                                                $newPath = null, 
                                                $maxwidth = 1000, 
                                                $maxheight = 1000, 
                                                $quality = 100)
    {
        if (is_null($newPath)) {
            $newPath = $filePath;
        }
        $gdImage = getimagesize($filePath);
        $actualWidth = $gdImage[0];
        $actualHeight = $gdImage[1];
        // Do we even need to resize the image!?
        if ($actualWidth <= $maxwidth && $actualHeight <= $maxheight){
            return array('result' => self::RESULT_RESIZE_NOT_REQUIRED,
                            'newHeight' => $actualHeight,
                            'newWidth' => $actualWidth);
        }
        $ratio = $actualWidth / $maxwidth;
        // echo "ratio : ".$ratio."<br />";
        // echo "Current dimensions: ".$actualWidth." : ".$actualHeight." : <br />";
        // set the defaults:
        $newWidth = intval($actualWidth);
        $newHeight = intval($actualHeight);     
        if ($actualWidth > $maxwidth) {
            $newWidth = intval($maxwidth);
            $newHeight = intval($actualHeight / $ratio);
        }
        // echo "After width process, dimensions: ".$newWidth." : ".$newHeight." : <br />";
        // once we've got the size width, is the height now small enough? 
        if ($newHeight > $maxheight) {
            // set a new ratio
            $ratio = $newHeight / $maxheight;
            $newWidth = intval($newWidth / $ratio);
            $newHeight = intval($maxheight);
        }       
        // echo "New dimensions: ".$newWidth." : ".$newHeight." : <br />";
        // Assign the class vars
        self::$_filePath = $filePath;
        self::$_newPath = $newPath;
        self::$_maxwidth = $maxwidth;
        self::$_maxheight = $maxheight;
        self::$_quality = $quality;
        self::$_newWidth = $newWidth;
        self::$_newHeight = $newHeight;
        self::$_actualWidth = $actualWidth;
        self::$_actualHeight = $actualHeight;
        switch (strtolower($gdImage['mime'])) {
            case 'image/jpeg':
                self::_createFromJpeg();
                break;
            case 'image/pjpeg':
                self::_createFromPJpeg();
                break;
            case 'image/png':
                self::_createFromPng();
                break;
            case 'image/gif':
                self::_createFromGif();
                break;
            default:
                throw new Exception('Mime Type ''' . $gdImage['mime'] . ''' not supported');
                break;
        }
        return array('result' => self::RESULT_RESIZE_SUCCESSFUL,
                        'newHeight' => $newHeight,
                        'newWidth' => $newWidth);
    }
    /**
     * Resizes images of type image/jpeg.
     *
     * @static 
     * @access private
     * @return void
     */
    private static function _createFromJpeg()
    {
        $img = imagecreatefromjpeg(self::$_filePath);
        $new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
        imagecopyresampled($new_img, 
                            $img, 
                            0, 
                            0, 
                            0, 
                            0, 
                            self::$_newWidth, 
                            self::$_newHeight, 
                            self::$_actualWidth, 
                            self::$_actualHeight);
        imagejpeg($new_img, self::$_newPath, self::$_quality);
    }
    /**
     * Resizes images of type image/jpeg.
     *
     * @static 
     * @access private
     * @return void
     */
    private static function _createFromPJpeg()
    {
        $img = imagecreatefromjpeg(self::$_filePath);
        imageinterlace($img, 1);
        $new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
        imagecopyresampled($new_img, 
                            $img, 
                            0, 
                            0, 
                            0, 
                            0, 
                            self::$_newWidth, 
                            self::$_newHeight, 
                            self::$_actualWidth, 
                            self::$_actualHeight);
        imagejpeg($new_img, self::$_newPath, self::$_quality);
    }
    /**
     * Resizes images of type image/png.
     *
     * @static 
     * @access private
     * @return void
     */
    private static function _createFromPng()
    {
        $img = imagecreatefrompng(self::$_filePath);
        $new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
        imagecopyresampled($new_img, 
                            $img, 
                            0, 
                            0, 
                            0, 
                            0, 
                            self::$_newWidth, 
                            self::$_newHeight, 
                            self::$_actualWidth, 
                            self::$_actualHeight);
        imagepng($new_img, self::$_newPath);        
    }
    /**
     * Resizes images of type image/gif.
     *
     * @static 
     * @access private
     * @return void
     */
    private static function _createFromGif()
    {
        $img = imagecreatefromgif(self::$_filePath);
        $new_img = imagecreatetruecolor(self::$_newWidth, self::$_newHeight);
        imagecopyresampled($new_img, 
                            $img, 
                            0, 
                            0, 
                            0, 
                            0, 
                            self::$_newWidth, 
                            self::$_newHeight, 
                            self::$_actualWidth, 
                            self::$_actualHeight);
        imagegif($new_img, self::$_newPath);    
    }
}

希望对你有帮助。

检索所有数据来查找新图像的名称是非常低效的。更好的解决方案是插入一条不存储文件名的记录,并从auto_increment id生成文件名(使用基本路径/some/where/photoploads/$bandid/)。

如果这还不是你最大的性能问题,那么很快就会了。

减少图片的大小也是一个好主意——就像检查重复一样。

如果有很多,那么页面将加载较慢

延迟加载下面的图片-有很多现成的脚本可以做到这一点(例如)