How can I convert base64 encoded data URL to a PNG image?
391 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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?
0 commentaires
Réponse acceptée
T.Nikhil kumar
le 21 Mai 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!
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Import and Export dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!