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

Storing image in database directly or as base64 data?(将图像直接存储在数据库中还是作为 base64 数据?)
本文介绍了将图像直接存储在数据库中还是作为 base64 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在数据库中存储图像的常用方法是在存储数据之前将图像转换为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.

      这篇关于将图像直接存储在数据库中还是作为 base64 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)