KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Utility Method to Take a Picture and Return its Base64 Text
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: October 11, 2022

Dealing with pictures can be tricky. Often times developers may need to work with a picture and that data may need to be converted into another type, such as text. One example would be if a developer was working with an object that contained a picture and that object needed to be stored in a JSON format. JSON is a form of text, so the first step would be to convert this picture into a text variable. Unfortunately there isn’t a 4D command to perform this task, but the Utility Method, named pic2Base64 will do just that.

This utility method pic2Base64 accept a picture and returns its safe Base64 Encoded text. From here the developer can convert this text to JSON if needed, and the picture will stay intact.

To ensure your picture isn’t lost, we must utilize the following 4D commands: PICTURE TO BLOB, BASE64 ENCODE, and Blob to text.

Here are the steps to the utility method and the code is provided below.
//1. Method accepts a picture as a parameter
//2. Picture converted to Blob
//3. Blob is passed to 4D Command Base64 Encode($blob)
//4. Blob to text($blob) -> store this into $encoded_t
//5. Return $encode_t

Utility Method Below - pic2Base64

#DECLARE($picture : Picture)->$encoded_t : Text

var $blob_b : Blob

PICTURE TO BLOB($picture; $blob_b; "image/jpeg")
BASE64 ENCODE($blob_b)
$encoded_t:=BLOB to text($blob_b; UTF8 text without length)


For Example:

$encoded_t:=pic2Base64($picture)


Content of $base64 Text variable:

/9j/4AAQSkZJRgABAQAAAQABAAD/

JkDIyDIGRkZMgZGRkyBkZBkDIyMkADywTAMWJgiABMLEADwqlQZQyh/9k=