· Sep 28 2m read

How to save and restore images in an object using Base64 strings

InterSystems FAQ rubric

In the sample below, an image file is encoded into a Base64 string in a class property, saved, decoded again with Base64, and restored to another file.

【Usage class】

Class User.test Extends %Persistent
Property pics As %GlobalBinaryStream;

【When importing】

  set x=##class(User.test).%New() // create a new object

  // prepare an image
  set file=##class(%File).%New("c:\temp\Mii.png")
  do file.Open("RUK\BIN\")
  for {
       if file.AtEnd=1 quit
       // Convert image to Base64 format in chunks of 1024 bytes
       set cnt=file.Read(1024)
       set b64=$system.Encryption.Base64Encode(cnt) // b64: 1402byte
  do x.%Save()
  do file.Close()

【When exporting from a property】

 // restore the file
 set file2=##class(%FileBinaryStream).%New()
 do file2.LinkToFile("C:\temp\xx.png")

 // Read from the database the User.test object
 set x=##class(User.test).%OpenId(1)

 for {
   if quit
   set cnt=$system.Encryption.Base64Decode(b64)
   do file2.Write(cnt)
 do file2.SaveStream()
Discussion (2)0
Log in or sign up to continue