1

This question has been asked before mentioning the lib or includes that provides a functional gallery, But i want to create one from scratch. So any ideas on the following

  1. Galleries need to be uploaded using Form and Browse(This i can find no Problem, just need it to be there to outline the steps)
  2. Need to have a thumbnail image created when a file is uploaded.
  3. How should it be structured in the Database, For example stored in DB as image or filename

Requirments

  • Only PHP and MySql

Any ideas? Please let me know if it cant be done as well :D

Thanks

4

2 回答 2

6

我将尝试回答您的问题:


问题 1

那部分其实很简单。要创建文件上传表单,您的 HTML 需要如下所示:

 <form enctype='multipart/form-data' action='CodeTool.php' method='POST'>
     File: <input name='picture' type='file'/>
     <input type='submit' value='Upload'/>
 </form>

您的表格需要拥有enctype='multipart/form-data'并且method需要POST。然后,要读取上传文件,您可以简单地使用以下内容。我还添加了一些基本验证以确保文件是图像。

 if(isset($_FILES['picture'])) {
     echo "File has been uploaded under temp file " . $_FILES['picture']['tmp_name'];

     // Let's check if the file is an image:
     $fileData = file_get_contents($_FILES['picture']['tmp_name']);

     // Using imagecreatefromstring, that way you don't need to
     // guess the image format.

     if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
         echo " and is a valid image";
     } else {
         echo " and is not a valid image";
     }
 }

问题2

要创建缩略图,您可以使用 GD(或 ImageMagick,但它不包含在默认配置中)这样......让我们继续imagecreatefromstring if声明:

if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
    // Let's create a 100x100 thumbnail
    $width = imagesx($img);
    $height = imagesy($img);

    $boxSize = min($width,$height);
    $boxX = ($width / 2) - ($boxSize / 2);
    $boxY = ($height / 2) - ($boxSize / 2);

    $thumb = imagecreatetruecolor(100, 100);
    imagecopyresampled($thumb, $img, 0, 0, $boxX, $boxY, 100, 100, $boxSize, $boxSize);

    //$thumb is now a 100x100 thumbnail
}

问题 3

在这里,您有 2 个选项。您可以将图像存储在文件系统或数据库中。要将图像存储在文件系统中,您可以执行以下操作:

if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
    move_uploaded_file($_FILES['picture']['tmp_file'], 'somefile.jpg');
    // the code from the previous example
    imagejpeg($thumb, 'somefile_thumb.jpg');
}

我个人更喜欢使用数据库来存储图像,因为它更容易保持引用完整性并使备份更简单(备份数据库就完成了)。它有点慢,但差异真的不是很大:

if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
    // the code from the previous example

    $tmp_thumb = tempnam(sys_get_temp_dir(), 'thumb');
    imagejpeg($thumb, $tmp_thumb);

    $thumbData = file_get_contents($tmp_thumb);

    mysql_query("INSERT INTO images (original, thumb) VALUES ('" . mysql_real_escape_string($fileData) . "', '" . mysql_real_escape_string($thumbData) . "');");
} 

字段必须是BLOB.

于 2009-08-05T01:34:46.607 回答
0

您几乎肯定会想要将图像存储在文件系统中,然后只需在 DB 条目中引用文件名\路径 - 它可以降低查询结果的大小,尤其是在您想要提取多个图像的信息时。如果您想使用它来创建缩略图,它还可以更容易地调用诸如 imagemagick 之类的东西。

于 2009-08-05T01:24:39.050 回答