Question
Fabio Care · Jul 27

Problem converting Image to Base64

Hello all, 

i am currently struggling following the instructions for reading an image file into the database as a base64 string.

My goal is to save an image into a global as base64. I followed different guides like:

https://community.intersystems.com/post/how-save-png-image-cache-base64-...

https://community.intersystems.com/post/how-save-fileimage-some-specific...

https://cedocs.intersystems.com/ens20152/csp/documatic/%25CSP.Documatic....

 

Here is my current code:

 FILE,BASE64
 Set file=##class(%Stream.FileBinary).%New()
 Set sc=file.LinkToFile("C:\Users\fcare\Desktop\1.png")
 Do file.Rewind()
 SET BASE64=""
 While 'file.AtEnd {
  Set BASE64=BASE64_file.Read()
 }
 BASE64=$ZCONVERT(BASE64,"O","UTF8")
 BASE64=$system.Encryption.Base64Encode(BASE64,1)

 

The resulting string however is not a valid base64 image format. I tested different images with different data types. Always the same result. Files also varied in size. 

Attached will be the original file aswell as the output for BASE64. 

   

Output:

 
Spoiler

 

Product version: Caché 2017.1
0
0 122
Discussion (5)1
Log in or sign up to continue

First of all, it's meaningless to post several KB of raw data. Either provide it somewhere for download or make an attachment (if possible).

Second, Base64 encodings converts 3 (incoming) bytes into 4 (outgoing) bytes, this means you always (except the last one) have to read multiple of 3 bytes at once, convert it, and put into the output stream. Your file.Read() reads 32000 bytes, which is NOT a multiple of 3!

Hi Julius, thanks for the answer. What function would I use to read multiples of 3 instead of 4? 

You can take the line from your own code, but with a suitable parameter

Set BASE64=BASE64_file.Read(someCount) // someCount = aNumber * 3

For example 30000 instead of 32000. By the way, you read (8 bit) bytes, so there is no need to do the output-UTF8 conversion.

Thank you very much! That fixed it.