将图像直接存储在数据库中还是作为base64数据存储?

2022-01-30 00:00:00 image database base64 imagemagick mysql

在数据库中存储图像的常用方法是在存储数据之前将图像转换为base64数据.这个过程将增加 33% 的大小.或者,可以将图像直接存储为 BLOB;例如:

The common method to store images in a database is to convert the image to base64 data before storing the data. This process will increase the size by 33%. Alternatively it is possible to directly store the image as a BLOB; for example:

$image = new Imagick("image.jpg");
$data = $image->getImageBlob();
$data = $mysqli->real_escape_string($data);
$mysqli->query("INSERT INTO images (data) VALUES ('$data')");

然后用

<img src="data:image/jpeg;base64,' .  base64_encode($data)  . '" />

使用后一种方法,我们节省了 1/3 的存储空间.为什么在 MySQL 数据库中将图像存储为 base64 更常见?

With the latter method, we save 1/3 storage space. Why is it more common to store images as base64 in MySQL databases?

更新:关于将图像存储在数据库中的优缺点有很多争论,大多数人认为这不是一种实用的方法.无论如何,在这里我假设我们将图像存储在数据库中,并讨论这样做的最佳方法.

UPDATE: There are many debates about advantages and disadvantages of storing images in databases, and most people believe it is not a practical approach. Anyway, here I assume we store image in database, and discussing the best method to do so.

推荐答案

  • Pro base64:您处理的编码表示是一个非常安全的字符串.它既不包含控制字符也不包含引号.后一点有助于防止 SQL 注入尝试.我不认为将值添加到手动编码"SQL 查询字符串会出现任何问题.

    • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

      Pro BLOB:数据库管理器软件知道它所期望的数据类型.它可以为此进行优化.如果您将 base64 存储在 TEXT 字段中,它可能会尝试为其构建一些索引或其他数据结构,这对于真实"文本数据来说非常好和有用,但对于图像数据毫无意义并且浪费时间和空间.它是较小的,如字节数,表示形式.

      Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

相关文章