How can I convert base64 encoded data URL to a PNG image?

362 visualizzazioni (ultimi 30 giorni)
I have image data in the form of base64 encoded data URLs, like this:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABdwAAAK8CAYAAAD1...'
I need to convert these to either some common image format, such as PNG, or JPEG, or directly to a matrix describing the image.
Matlab provides "webread" to read data from web services, but this does not support the "data:" protocol.
Is there a way to use Matlab to read data URLs?

Risposta accettata

T.Nikhil kumar
T.Nikhil kumar il 21 Mag 2024
Hello David,
I understand that you are looking for a way to convert your image in form of base64 data to a PNG/JPEG.
I would suggest you to use ‘matlab.net.base64decode’ function for this purpose. After decoding, you will get the binary representation of the image. You can write this binary data to a file with the appropriate extension (e.g., .png, .jpeg) using ‘fwrite’. Follow the steps as mentioned below:
- You first need to extract the base64 encoded part of the data URL, which is the portion after the comma.
dataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUh…..==';
commaIndex = strfind(dataURL, ',');
base64String = dataURL(commaIndex+1:end);
- Decode the base64 string using the ‘matlab.net.base64decode’ function.
decodedBytes = matlab.net.base64decode(base64String);
- Write the data to an image File
fileName = 'outputImage.png'; % or .jpeg, depending on the data
fid = fopen(fileName, 'wb');
fwrite(fid, decodedBytes);
fclose(fid);
Now you have your image ‘outputImage.png’ saved in the current folder.
Refer to the following documentation for more understanding of functions used above:
Hope this helps!

Più risposte (0)

Categorie

Scopri di più su Data Import and Export in Help Center e File Exchange

Prodotti


Release

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by