user6325753
user6325753

Reputation: 577

image encoding and decoding in mysql using python

i am trying to read the image as input and convert this as base64 type and store it into mysql db.

and again read the base64 string from mysql and send the data as response to front-end.

what i tried so far is:

with open('/home/user/Desktop/image1.png', 'rb') as binary_file:
    binary_file_data = binary_file.read()

i am storing binary_file_data value into mysql blob column.

is this correct way to store base64 in mysql?

and how to read this base64 data from mysql and send as response to front-end in python?

any suggestions please.

Upvotes: 0

Views: 246

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562368

You don't need to use base64 to store binary data in a BLOB data type.

Encoding in base64 transforms three bytes of binary data into four bytes of base-64 encoded characters, so it can use only printable ASCII symbols. By doing this, it increases the total size of your data by 33%.

BLOBs can store full 8-bit bytes, and they don't care about bytes that are unprintable. So you can just store the bytes as-is.

That is, once you load the content of your image file into your variable binary_file_data, then just store that directly into the BLOB column using the INSERT SQL statement. Don't encode it.


Re your comments:

The way http works is that each image is a separate http request, so you need to make another PHP script to fetch the BLOB from the database and echo it:

<?php

header('Content-Type: image/png');

// query BLOB data from database

// echo BLOB data

Then in your main PHP script that outputs HTML, you reference the one that reads the image from the database:

<img src="/myimage.php">

As long as the PHP script sets the content-type, it works just as well as reading the image file from disk.

Upvotes: 1

Related Questions