How can I encode images to Base64?

56 views (last 30 days)
Laszlo
Laszlo on 5 Dec 2023
Edited: Hassaan on 22 Jan 2024
Hi, I want to encode an image to Base64, but the result is completely different than when I encode the image on this page.
I don't understand what I am doing wrong, is it me or the page I am using?
Here is my code (Google Bard helped me):
function encoded_string = base64encode_image(image)
image_uint8 = im2uint8(image);
encoded_bytes = zeros(1, length(image_uint8) * 4 / 3);
for i = 1:length(image_uint8)
encoded_bytes(4 * (i - 1) + 1:4 * i) = base64_chars(image_uint8(i) / 64 + 1);
encoded_bytes(4 * i + 1:4 * i + 2) = base64_chars((image_uint8(i) % 64) / 8 + 1);
encoded_bytes(4 * i + 2:4 * i + 3) = base64_chars((image_uint8(i) % 8) + 1);
end
encoded_string = char(encoded_bytes);
while length(encoded_string) % 3 ~= 0
encoded_string = [encoded_string "="];
end
end
Thank you!
  8 Comments
Dyuman Joshi
Dyuman Joshi on 5 Dec 2023
Hmmm. So, I asked the AI the same thing as well. I have attached pictures as to how it went.
which base64encode -all
'base64encode' not found.
And it was a bit weird. It references a function that does not exist and mentions the latest version as R2021a.
I tested for the function in my R2021a as well, but it had the same output i.e. not found.
But I did find this - matlab.net.base64encode, but that expects the inputs as either string, character vector or a numeric vector.
DGM
DGM on 6 Dec 2023
Edited: DGM on 6 Dec 2023
Aside from the AI being consistently misleading about how to access it and how to use it, that could be used. At least that would avoid a FEX dependency.
% encode only the raw image data
inpict = imread('peppers.png');
V = matlab.net.base64encode(inpict(:));
outpict = matlab.net.base64decode(V);
outpict = reshape(outpict,size(inpict));
imshow(outpict)
As to whether it matches some other encoder, I suppose that depends on what you're comparing. If you encode a JPG image, you're encoding the entire file as a byte stream -- the header, the metadata, the compressed raster data. If you read the image with imread(), you're just encoding an arbitrarily vectorized bunch of raw uncompressed image data. If you fed the latter to your web browser, it probably wouldn't know what to do with it.
% encode the file itself
fid = fopen('peppers.png');
V = fread(fid,'*uint8');
fclose(fid);
V = matlab.net.base64encode(V); % a web browser could read this

Sign in to comment.

Accepted Answer

Hassaan
Hassaan on 18 Jan 2024
Edited: Hassaan on 22 Jan 2024
@Laszlo Try this out and matches the online tool.
To correctly encode a JPEG image to Base64 in MATLAB, the key is to read the image file as a raw byte stream, not as an image. This is because when MATLAB reads an image using imread, it converts the image into a matrix format suitable for image processing, which is not what you want for Base64 encoding.
  1. Read the JPEG image file as raw bytes.
  2. Encode these bytes into a Base64 string.
Image Input
% Specify the path to your JPEG image
imagePath = 'image.jpeg';
% Open the file in binary read mode
fileID = fopen(imagePath, 'rb');
% Read the file as bytes
imageBytes = fread(fileID, '*uint8');
% Close the file
fclose(fileID);
% Encode the byte array into Base64
encodedBase64 = matlab.net.base64encode(imageBytes);
% Display the Base64 encoded string using 'matlab.net.base64encode'
disp(encodedBase64);
% Encode the byte array into Base64 using custom function 'base64encode'
encodedBase64Custom = base64encode(imageBytes);
% Display the Base64 encoded string using my custom function
disp(encodedBase64);
% This function takes an array of uint8 data, converts it to a binary string,
% chunks this string into 6-bit segments, maps these to Base64 characters,
% and adds necessary padding.
function encodedString = base64encode(inputData)
% Define the Base64 characters
base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
% Convert input data to uint8 if it's not already
if ~isa(inputData, 'uint8')
error('Input must be a uint8 array.');
end
% Convert the data to binary string
binaryString = reshape(dec2bin(inputData, 8)', 1, []);
% Pad the binary string so its length is a multiple of 6
paddedBinaryString = [binaryString, repmat('0', 1, mod(-length(binaryString), 6))];
% Initialize the encoded string
encodedString = '';
% Map each 6-bit chunk to a Base64 character
for i = 1:6:length(paddedBinaryString)
sixBitChunk = paddedBinaryString(i:i+5);
decimalValue = bin2dec(sixBitChunk);
encodedString = [encodedString, base64Chars(decimalValue+1)];
end
% Add padding characters
paddingLength = mod(-length(inputData), 3);
if paddingLength > 0
encodedString(end+1:end+paddingLength) = '=';
end
end
MATLAB code with my image:
/9j/4AAQSkZJRgABAQEA8ADwAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ ...
/9j/4AAQSkZJRgABAQEA8ADwAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ ...
Will read the JPEG image as a binary file, preserving its original byte format, and then encode these bytes into a Base64 string.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.
  2 Comments
Dyuman Joshi
Dyuman Joshi on 18 Jan 2024
Which image and online tool did you use?
You should mention such details in the answer itself.

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!