如何使用 PHP 从 MySQL 数据库中存储和检索图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1636877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:20:55  来源:igfitidea点击:

How can I store and retrieve images from a MySQL database using PHP?

phpmysqldatabaseblob

提问by Mask

How can I insert an image in MySQL and then retrieve it using PHP?

如何在 MySQL 中插入图像,然后使用 PHP 检索它?

I have limited experience in either area, and I could use a little code to get me started in figuring this out.

我在这两个领域的经验都有限,我可以使用一些代码来开始解决这个问题。

回答by Andomar

First you create a MySQL table to store images, like for example:

首先创建一个 MySQL 表来存储图像,例如:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

然后您可以将图像写入数据库,例如:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

您可以在网页中显示来自数据库的图像:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

回答by Ankit Sharma

Instead of storing images in database store them in a folder in your disk and store their location in your data base.

不是将图像存储在数据库中,而是将它们存储在磁盘中的文件夹中,并将它们的位置存储在数据库中。

回答by Kornel

Beware that serving images from DB is usually much, much muchslower than serving them from disk.

请注意,从数据库提供图像通常比从磁盘提供图像慢得多。

You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.

您将启动一个 PHP 进程,打开一个 DB 连接,让 DB 从与文件系统相同的磁盘和 RAM 读取图像数据以进行缓存,通过几个套接字和缓冲区传输它,然后通过 PHP 推出,默认情况下,它不可缓存并增加了分块 HTTP 编码的开销。

OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead.

OTOH 现代 Web 服务器可以通过少量优化的内核调用(内存映射文件和传递给 TCP 堆栈的内存区域)来提供图像,因此它们甚至不会复制内存,并且几乎没有开销。

That's a difference between being able to serve 20 or 2000 images in parallel on one machine.

这是能够在一台机器上并行提供 20 或 2000 张图像的区别。

So don't do itunless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.

所以不要这样做,除非您绝对需要事务完整性(实际上甚至可以通过数据库中的图像元数据和文件系统清理例程来完成)并且知道如何改进 PHP 对 HTTP 的处理以适合图像。

回答by Scott Evernden

i also recommend thinking this thru and then choosing to store images in your file system rather than the DB .. see here: Storing Images in DB - Yea or Nay?

我还建议想这通,然后选择存储图像文件系统,而不是DB ..在这里看到:在数据库中存储的图像-是啊,还是不是?

回答by Gunaseelan

My opinion is, Instead of storing images directly to the database, It is recommended to store the image location in the database. As we compare both options, Storing images in the database is safe for security purpose. Disadvantage are

我的观点是,与其直接将图片存储到数据库中,不如将图片位置存储在数据库中。当我们比较这两个选项时,出于安全目的,将图像存储在数据库中是安全的。缺点是

  1. If database is corrupted, no way to retrieve.

  2. Retrieving image files from db is slow when compare to other option.

  1. 如果数据库损坏,则无法检索。

  2. 与其他选项相比,从 db 检索图像文件很慢。

On the other hand, storing image file location in db will have following advantages.

另一方面,将图像文件位置存储在 db 中将具有以下优点。

  1. It is easy to retrieve.

  2. If more than one images are stored, we can easily retrieve image information.

  1. 很容易找回。

  2. 如果存储了多个图像,我们可以轻松检索图像信息。

回答by exussum

Personally i wouldnt store the image in the database, Instead put it in a folder not accessable from outside, and use the database for keeping track of its location. keeps database size down and you can just include it by using PHP. There would be no way without PHP to access that image then

我个人不会将图像存储在数据库中,而是将其放在一个无法从外部访问的文件夹中,并使用数据库来跟踪其位置。保持数据库大小减小,您可以使用 PHP 将其包含在内。如果没有 PHP 就无法访问该图像