Thread overview | |||||
---|---|---|---|---|---|
|
July 30, 2020 How do I convert a Base64 image url string to a png/jpg image file? | ||||
---|---|---|---|---|
| ||||
So I have a base64 image url string and I'm trying to generate a png,jpg image file from it. I'm able to decode it to a buffer but the trouble is getting it from buffer to an actual image file. Any library function combination I can use? |
July 30, 2020 Re: How do I convert a Base64 image url string to a png/jpg image file? | ||||
---|---|---|---|---|
| ||||
Posted in reply to aberba | On Thursday, 30 July 2020 at 12:22:46 UTC, aberba wrote:
> I'm able to decode it to a buffer but the trouble is getting it from buffer to an actual image file. Any library function combination I can use?
I don't think I wrote it as a library yet, but the idea is pretty simple: they all start with "data:" so you look for that.
Then there's a type after that, so you read the string until the next ; character. It will be like image/png or image/jpeg.
Then there's the semicolon and the string "base64,".
After that, the rest of the string is base64 data.
```
import std.base64;
ubyte[] data = Base64.decode(rest_of_string);
```
And now that you have the data you can write it to a file:
```
import std.file;
std.file.write("filename.png", data);
```
And that should make the file you want.
|
July 30, 2020 Re: How do I convert a Base64 image url string to a png/jpg image file? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Adam D. Ruppe | On Thursday, 30 July 2020 at 12:28:08 UTC, Adam D. Ruppe wrote: > On Thursday, 30 July 2020 at 12:22:46 UTC, aberba wrote: >> [...] > > I don't think I wrote it as a library yet, but the idea is pretty simple: they all start with "data:" so you look for that. > > Then there's a type after that, so you read the string until the next ; character. It will be like image/png or image/jpeg. > > Then there's the semicolon and the string "base64,". > > After that, the rest of the string is base64 data. > > ``` > import std.base64; > ubyte[] data = Base64.decode(rest_of_string); > ``` > > And now that you have the data you can write it to a file: > ⅞iii> import std.file; > std.file.write("filename.png", data); > ``` > > And that should make the file you want. Thank Adam. |
Copyright © 1999-2021 by the D Language Foundation