필터 지우기
필터 지우기

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

조회 수: 163 (최근 30일)
David
David 2024년 5월 20일
댓글: David 2024년 5월 21일
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?

채택된 답변

T.Nikhil kumar
T.Nikhil kumar 2024년 5월 21일
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!

추가 답변 (0개)

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by