How to read and show image from database?

4 views (last 30 days)
Fatimah Selamat
Fatimah Selamat on 20 Apr 2018
Answered: Madheswaran on 21 Jan 2025
I'm currently doing image processing, I had already created the database (982x2) where column 1 for RGB and column 2 for grayscale for all the images but I want to check whether the database is correct or not. So I want to read and show the image but I don't know how to read the image by its row and column. Can anyone help me? Thank you in advance.

Answers (1)

Madheswaran
Madheswaran on 21 Jan 2025
Hello Fatimah,
If you're utilizing a relational database such as MySQL to store images in BLOB (Binary Large Object) format, you can retrieve the binary data, convert it to 'uint8' format, and save it temporarily as an image file for visualization. Below is a sample table structure and corresponding MATLAB code to visualize images stored in the 'image_data' column of 'images' table.
Here is the table structure that I used in the below sample code:
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| image_data | longblob | YES | | NULL | |
+------------+----------+------+-----+---------+----------------+
You can extend the below code to suit your specific requirements. Also, ensure that you set the correct file extension when saving the temporary image file.
tableName = 'images';
rowNumber = 5;
sqlQuery = sprintf('SELECT image_data FROM %s WHERE id = %d', tableName, rowNumber);
result = fetch(conn, sqlQuery) %conn is database connection object
blob_data = result.image_data{1}; % Get the BLOB data from the cell array
image_data = typecast(blob_data, 'uint8');
% Create a temporary file to save the image data
temp_filename = 'temp_image.jpg'; % Adjust extension based on your image type
fileID = fopen(temp_filename, 'w');
fwrite(fileID, image_data);
fclose(fileID);
img = imread(temp_filename);
figure;
title(sprintf('Image from row %d', rowNumber));
imshow(img);
delete(temp_filename);
For more information, refer to the following documentations:
  1. fwrite - https://mathworks.com/help/matlab/ref/fwrite.html
  2. imread - https://mathworks.com/help/matlab/ref/imread.html
  3. imshow - https://mathworks.com/help/matlab/ref/imshow.html
I hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!