如何从头开始创建基于PHP/MySQL的图像库?

Ang*_*.47 1 php mysql gallery

在提到lib或包含提供功能库之前已经问过这个问题,但我想从头开始创建一个.所以关于以下的任何想法

  1. 需要使用表单和浏览上传图库(我可以找到没有问题,只需要在那里概述步骤)
  2. 需要在上载文件时创建缩略图图像.
  3. 它应该如何在数据库中构建,例如存储在DB中作为图像或文件名

质量要求

  • 只有PHP和MySql

有任何想法吗?如果不能这样做,请告诉我:D

谢谢

And*_*ore 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>
Run Code Online (Sandbox Code Playgroud)

你的表格需要有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";
     }
 }
Run Code Online (Sandbox Code Playgroud)

问题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
}
Run Code Online (Sandbox Code Playgroud)

问题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');
}
Run Code Online (Sandbox Code Playgroud)

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

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) . "');");
} 
Run Code Online (Sandbox Code Playgroud)

这些领域需要BLOB.