Knowledge Base

Get Base64 representation of chart image

This demo shows how you can use Export plugin’s API to generate a Base64 snapshot of the chart’s appearance.

It’s useful when you want to export the chart for saving on server or showing as in-line image.

The built-in export menu is disabled by setting menu parameter to an empty array: [].

On client

In your browser, once you export to Base64, you can transfer to your server, using AJAX. Here’s an example using jQuery:

function exportChart() {
  chart["export"].capture({}, function() {

    // SAVE TO PNG
    this.toPNG({}, function(base64) {

      // We have now a Base64-encoded image data
      // which we can now transfer to server via AJAX
      jQuery.post("saveimage.php", {
        "data": base64
      })
    });
  });
}

On server

On server-side, you would just need to parse the Base64 and save the actual file. Here’s an example PHP function that does that:

function save_image_file( $base64, $upload_dir ){
  $needle = strpos( $base64, ',' );

  if ( $needle !== false ) {
    $base64  = substr( $base64, $needle + 1 );
    $data    = base64_decode( $base64 );
    $uid     = uniqid();
    $file    = $uid . '.png';
    $success = file_put_contents( $upload_dir . '/' . $file, $data );

    return $success ? $uid : false;
  }

  return false;
}