· Feb 11, 2018

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


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:

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.



Discussion (2)0
Log in or sign up to continue

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 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.