Alan Wells
Alan Wells

Reputation: 31300

Google Apps Script - Convert base 64 Image source to an image file

Here is an example of an image tag with the image source as base 64 data. The base 64 data is a smiley face.

<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">

I want to use base64 data to create an image file in Google Drive.

I've tried the following code, which runs, and creates a file with no errors, but it won't open as an image file.

function createImageFileFromBase64() {
  var data = 'R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7';

  var imageBlob = Utilities.newBlob(data, 'image/png');

  var resource = {
    title: 'AAA Test_Image',
    mimeType: 'image/png'
  }

  var theReturn = Drive.Files.insert(resource,imageBlob );

  Logger.log('file ID: ' + theReturn.id);
}

My goal is to make an image file without making an external request to an image file. I want the image data to be "hard coded" into the script.

Upvotes: 0

Views: 2462

Answers (1)

TheMaster
TheMaster

Reputation: 50462

Create the blob using byte array created by decoding the base64 string:

var imageBlob = Utilities.newBlob(Utilities.base64Decode(data), 'image/png');

Upvotes: 2

Related Questions