KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Inserting and reading back pictures as base 64 text in a Collection
PRODUCT: 4D | VERSION: 17 | PLATFORM: Mac & Win
Published On: May 2, 2019

A picture can be inserted in a Collection. But also a picture can be encoded in base64 text which can then be inserted in a Collection as text. Here is a utility method to insert a picture and as well as read back in a Collection:

// ----------------------------------------------------------------------
// Name: INSERT_READBACK_PICTURE_COL
// Description: Method will insert a picture that is converted to blob
// base64 text into a collection. It will also read back a collection
// item that is blob base64 text to a picture variable.
//
// Parameters:
// $1 (POINTER) - Pointer to a collection to insert or readback
// $2 (LONGINT) - Location to insert or readback a picture
// $3 (POINTER) - Pointe to a picture that is inserted or read back
// $4 (TEXT) - Codec text to insert a picture for base64 encoding
// ----------------------------------------------------------------------
C_POINTER($1;$col)
C_LONGINT($2;$index)
C_POINTER($3;$pic)
C_TEXT($4;$codec;$blobText)
C_BLOB($blob)

If (Count parameters>2)
  $col:=$1
  $index:=$2
  $pic:=$3

  If (Count parameters=4) // Set a picture in collection
    $codec:=$4

    If (Type($pic->)=Is picture)
      PICTURE TO BLOB($pic->;$blob;$codec)
      BASE64 ENCODE($blob;$blobText)
      $col->[$index]:=$blobText
    End if

  Else // Read back a collection item to a picture
   $blobText:=$col->[$index]
   BASE64 DECODE($blobText;$blob)
   BLOB TO PICTURE($blob;$pic->)
  End if

End if


Here is an example of using the method by inserting a picture in a Collection:

C_TEXT($loc)
C_PICTURE($pic)
C_COLLECTION(col)

$loc:=Get 4D folder(Database folder)+"picture.png"
READ PICTURE FILE($loc;$pic)

col:=New collection(True;2323.434;2323;"hi")

INSERT_READBACK_PICTURE_COL (->col;4;->$pic;".jpg")


The base64 text of the picture is inserted in the Collection:



Using the same method can read back the picture to a variable:

INSERT_READBACK_PICTURE_COL (->col;4;->picVariable)



Commented by Kirk Brooks on May 23, 2019 at 6:53 AM
Great tip. I think it would be good to add "SET BLOB SIZE($blob;0)" as the last line of the method to avoid orphan blobs.