How can I encode images to Base64?
    42 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Laszlo
 el 5 de Dic. de 2023
  
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 comentarios
  Dyuman Joshi
      
      
 el 5 de Dic. de 2023
				Hmmm. So, I asked the AI the same thing as well. I have attached pictures as to how it went. 
which base64encode -all
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
      
      
 el 6 de Dic. de 2023
				
      Editada: DGM
      
      
 el 6 de Dic. de 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
Respuesta aceptada
  Hassaan
      
 el 18 de En. de 2024
        
      Editada: Hassaan
      
 el 22 de En. de 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.
- Read the JPEG image file as raw bytes.
- 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 comentarios
  Dyuman Joshi
      
      
 el 18 de En. de 2024
				Which image and online tool did you use?
You should mention such details in the answer itself.
  Hassaan
      
 el 18 de En. de 2024
				
      Editada: Hassaan
      
 el 18 de En. de 2024
  
			@Dyuman Joshi The same tool the OP mentioned:
I have updated.
Más respuestas (0)
Ver también
Categorías
				Más información sobre Convert Image Type en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




