Skip to content

Instantly share code, notes, and snippets.

@yuya
Last active January 4, 2016 18:59
Show Gist options
  • Save yuya/8664592 to your computer and use it in GitHub Desktop.
Save yuya/8664592 to your computer and use it in GitHub Desktop.
Google Apps Script で簡易 Base64Encoder
function getImageBase64(source) {
var image = UrlFetchApp.fetch(source),
blob, contentType, base64;
if (!image) {
return;
}
blob = image.getBlob();
contentType = blob.getContentType();
base64 = Utilities.base64Encode(blob.getBytes());
return "data:" + contentType + ";base64," + base64;
}
function doGet(req) {
if (!req) {
return;
}
var source = req.parameters.src,
callback = req.parameters.callback ? req.parameters.callback : "callback",
response = getImageBase64(source),
mimeType = "JSON";
return ContentService.createTextOutput(callback + "(" + JSON.stringify({ data : response }) + ")")
.setMimeType(ContentService.MimeType[mimeType]);
}
@yuya
Copy link
Author

yuya commented Jan 28, 2014

使うときは下記のように JSONP で base64 の文字列を受け取る

var GAS_URL = "//script.google.com/macros/s/AKfycbyk4aLiJyVF4D10nio1ZtvS4Cb-DrB-1ROPdKWAoM2Z4-D_iRY/exec",
    IMG_URL = "https://github.global.ssl.fastly.net/images/modules/logos_page/GitHub-Logo.png",
    body, script, img, base64;

body   = document.body;
script = document.createElement("script");
img    = new Image();

window.callback = function (res) {
    base64  = res.data;
    img.src = base64;

    body.appendChild(img);    
    window.callback = null;
};

script.src = GAS_URL + "?src=" + IMG_URL;
body.appendChild(script);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment