Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using base64-encoded images with HtmlService in Apps Script

Does Google Apps Script support the use of base64-encoded images with HTML service? I am trying to add images to an HTML page using base64 encoding, but they are not displaying in the final page.

The HTML I am trying to use is:

<img src="data:'+contentType+';base64,'+encoded+'"/>

When I log the html content just before it is rendered by HTML service this appears as:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUh.....(base64 string)/>

This works fine in JSFiddle and in normal HTML, but in Apps Script, the images do not display. When viewing the source code on the rendered page, the image tags appear as follows:

<img src="null">

Is there another way to add base64-encoded images to the page? I can get the images as a blob, but I don't think there is a way to directly add a blob to the HTML content.

like image 268
StuWatson Avatar asked Dec 18 '13 11:12

StuWatson


4 Answers

To get the encoded base64 string in the first place from Google Drive files:

GS

var response = UrlFetchApp.fetch('https://googledrive.com/host/fileId/name.png');
var blob = response.getBlob();
var bytes = blob.getBytes();
var base64String = Utilities.base64Encode(bytes);
Logger.log(base64String);
// now copy and paste into html

HTML

<img src="data:image/png;base64, <base64String>" alt="img name" />
like image 80
Bryan P Avatar answered Nov 05 '22 11:11

Bryan P


As of December 2014, Google Apps Script has added an additional IFRAME sandbox mode, which supports data URIs (since it does not use the Caja compiler). The downside is that IFRAME mode is not compatible with older browsers, but depending on your requirements that may not be an issue.

All that's required is to call setSandboxMode() on your template, and your data URIs should work as expected:

var output = HtmlService.createHtmlOutput(
  '<img src="data:' + contentType + ';base64,' + encoded + '"/>'
);

output.setSandboxMode(HtmlService.SandboxMode.IFRAME);
like image 2
hopper Avatar answered Nov 05 '22 12:11

hopper


This is Issue 1558 for the Google Caja compiler - visit and star it to "vote" and receive updates. Have you tried testing in the Caja Testbed?

An alternative may be to have a server-side function retrieve the base64 encoded image via UrlFetch, decode it using base64Decode, then save the blob as an image file and host it from Google Drive. I expect this would be very slow, unfortunately.

like image 2
Mogsdad Avatar answered Nov 05 '22 11:11

Mogsdad


in GS

getImage64 = function(imageurl) {
var response = UrlFetchApp.fetch(imageurl);
var blob = response.getBlob();
var bytes = blob.getBytes();
return base64String = Utilities.base64Encode(bytes);
}
imgString = getImage64('https://URL.com/host/fileId/name.png');

HTML

<img src="data:image/png;base64, <imgString>" alt="img name" />
like image 1
Rei Aguilera Avatar answered Nov 05 '22 13:11

Rei Aguilera