Organizational Research By

Surprising Reserch Topic

storing image in database directly or as base64 data

storing image in database directly or as base64 data  using -'mysql,database,image,imagemagick,base64'

The common method to store images in database is to convert image to base64 data then storing. This process will increase the size 33%. Alternatively it is possible to directly store image 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')");

and display the image with

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

By the latter method, we save 1/3 storage space. Why storing base64 data into database is the common method for storing images in database?

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.

asked Sep 22, 2015 by vijayshukla80
0 votes

Related Hot Questions

3 Answers

0 votes

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: 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.

answered Sep 22, 2015 by pradip.bhoge
0 votes

in my opinion you DONT store binary data in the database, it just makes no sense. (ok.. there are very little exceptions..)

you store the location of the file (link, url..) in a database, not the file itself.

besides that see What is the best format to store images in a database?

answered Sep 22, 2015 by rajesh
0 votes

I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).

Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.

Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).

Do not store your images base64 encoded.

answered Sep 22, 2015 by android_master