How to save a PNG image in Cache, from a base64 data string

Hi,

Is it possible to Save a base64 data string, representing a png, as a binary png file, In Cache?

When I search google , in general , not Cache specifically,  I see such articles:

https://stackoverflow.com/questions/11511511/how-to-save-a-png-image-ser...

and this answer:

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

But I don't know how to implement that in Cache.

 

Regards,

Nael

 

  • 0
  • 0
  • 856
  • 1
  • 1

Answers

With Base64 possible to encode everything, text or binary data, such as PNG. To store it you should first decode it. But, if your image in DataURI format, first, you have to get only base64.

set png="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
set b64=$piece(png,"base64,", 2)

To encode Base64 in Caché you can use $system.Encryption.Base64Encode(), and $system.Encryption.Base64Decode()  to decode.

set binary=$system.Encryption.Base64Decode(b64)

But these methods support only string and does not support streams. So, you have to write this encoded data, to your file content. Do not forget to use Binary stream classes (%Stream.FileBinary, %Stream.GLobalBinary) to store binary information.

set file=##class(%Stream.GlobalBinary).%New()
do file.Write(binary)

But if your Base64 too long, you can decode by parts with length divisible by 3.