The IDL_BASE64 function uses MIME Base64 encoding to convert a byte array into a Base64 encoded scalar string, or to convert a Base64-encoded scalar string into a byte array.

The MIME Base64 encoding uses 64 characters, consisting of “A-Z”, “a-z”, “0-9”, “+”, and “/”. Every 3 bytes of the original array are converted into 4 characters. If the length of the final encoded string is not a multiple of 4, then it is padded with “=” characters. The 64 characters used in Base64 encoding were chosen because they are common to most character encodings, are printable, and are unlikely to be modified in transit through systems such as electronic mail.

This routine is written in the IDL language. Its source code can be found in the file in the lib subdirectory of the IDL distribution.


This example reads a JPEG image into a byte array, converts the array to a MIME Base64-encoded string, then converts the string back into a byte array and displays the two images side by side.

; Read an image into a byte array
READ_JPEG, FILEPATH('rose.jpg', $
   SUBDIRECTORY=['examples', 'data']), rose
; View the size of the byte array
HELP, rose
; Save the dimensions of the byte array
rs = SIZE(rose)
rose_dims = [rs[1], rs[2], rs[3]]
; Encode the byte array as a scalar string
rose_encoded = IDL_BASE64(rose)
; View information about the scalar string
HELP, rose_encoded
PRINT, 'rose_encoded is ' + STRING(STRLEN(rose_encoded)) $
   +' characters long'
;Decode the scalar string
rose2 = IDL_BASE64(rose_encoded)
; Note that the returned value is a byte vector 
HELP, rose2
; Reform the byte vector into an array of the
; same size as the original array
rose3 = REFORM(rose2, rose_dims)
HELP, rose3
; Display the original and reconstituted images
WINDOW, XSIZE=rose_dims[1]*2, YSIZE=rose_dims[2], $
   TITLE='Original and Reconstituted images', /FREE
TV, rose, 0, /TRUE
TV, rose3, 1,  /TRUE

This example converts an “ordinary” string into a Base64-encoded string:

; Use any ordinary string, which can contain 'unsafe'
; characters like spaces or exclamation marks:
orig_string = 'IDL is fun!'
; Convert the string to a byte array
orig_bytes = BYTE(orig_string)
; Note that the original string and byte array are the same size
HELP, orig_string
PRINT, STRLEN(orig_string)
HELP, orig_bytes
; Convert the byte array into an encoded string
new_string = IDL_BASE64(orig_bytes)
; Notice that the encoded string is larger than
; the original, and contains only 'safe' characters
PRINT, new_string
; To recover the original string:
PRINT, STRING(IDL_BASE64(new_string))


Result = IDL_BASE64(Input)

Return Value

If Input is a byte array, Result is a scalar string containing the Base64 encoded data.

If Input is a Base64 encoded string, Result is a byte vector containing the decoded data.



Input must be either an array of type byte or a Base64 encoded scalar string.



Version History