Is it wise to store base64 encoded images inside a database?

10,809

Solution 1

A base64 encoded image takes too much place (about 33% more than the binary equivalent).

MySQL offers binary formats (BLOB, MEDIUM_BLOB), use them.

Alternatively, most people prefer to store in the DB only a key to a file that the filesystem will store more efficiently, especially if it's a big image. That's the solution I prefer for the long term. I usually use a SHA1 hash of the file content to form the path to the file, so that I have no double storage and that it's easy to retrieve the record from the file if I want to (I use a three level file tree, first two levels being made respectively from the first two characters and the characters 3 and 4 of the hash so that I don't have too many direct child of a directory). Note that this is for example the logic of the git storage.

The advantage of storing them in the DB is that you'll manage more easily the backups, especially as long as your project is small. The database will offer you a cache, but your server and the client too, it's hard to decide a priori which will be fastest and the difference won't be big (I suppose you don't make too many concurrent write).

Solution 2

You could always save the base64_encode($image) in a file and only store the file path in the database, then use fopen() to get the encoded image.

My apologies if I didn't understand the question correctly.

Solution 3

I've done it both ways, and every time I come back to code where I stored binary data in a MySQL table I always switch it to filesystem with a pointer in the MySQL table.

When it comes to performance, you're going to be much better off going to the FS as pulling multiple large BLOBs from a MySQL server will tend to saturate its pipe quickly. Usually it's a pipe you don't want clogged.

Share:
10,809
dotty
Author by

dotty

Hmm not alot really.

Updated on June 20, 2022

Comments

  • dotty
    dotty almost 2 years

    I'm making an android application which takes a photo and push the image (as a base64 encoded string) to a PHP script, from here I'll be storing data about the image inside a MySQL database.

    Would it be wise to store the image inside the database (since it's passed as a base64 string), would it be better to convert it back to an image and store it on the filesystem?