Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Data URI using Google Apps Script Blob

I am trying to upload and save an image from Data URI in Google Apps Script. Everything works apart from the file type being set.

I've tried all variations of newBlob as per the Apps Script documentation.

function doUpload(dataURI) {

var folder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxxx");
var type = (dataURI.split(";")[0]).replace('data:','');
var imageUpload = Utilities.base64Decode(dataURI.split(",")[1]);
var blob = Utilities.newBlob(imageUpload, type, "nameOfImage");
folder.createFile(blob);

return true;
}
like image 661
herman Avatar asked Feb 27 '26 21:02

herman


2 Answers

Here is the small and important modification...

function doUpload(dataURI) {

var folder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxxx");
var type = (dataURI.split(";")[0]).replace('data:','');
var imageUpload = Utilities.base64Decode(dataURI.split(",")[1]);
var blob = Utilities.newBlob(imageUpload, type, "nameOfImage.png");
folder.createFile(blob);

return true;
}
like image 105
Akash Shendage Avatar answered Mar 01 '26 11:03

Akash Shendage


Converting and Saving Images as DataURI's

I get the images from a url using UrlFetch. If you don't have a place to host them then just put them in Google Photo Library and copy the url from there it works too. That way you can do all your image process for web ready artwork before you convert them with standard image editors.

function convImageUrl(url){
  var url=url || "http://jimesteban.com/images/mimincoopers.png";
  var blob=UrlFetchApp.fetch(url).getBlob();
  var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
  return b64Url;
}

function saveDataURIInFile(filename,datauri,type) {
  Logger.log('filename: %s\ndatauri: %s\ntype: %s\n',filename,datauri,type);
  if(filename && datauri && type) {
    var folder=DriveApp.getFolderById(getGlobal('MediaFolderId'));
    var files=folder.getFilesByName(filename);
    while(files.hasNext()) {
      files.next().setTrashed(true);
    }
    var f=folder.createFile(filename,datauri,MimeType.PLAIN_TEXT);
    return {name:f.getName(),id:f.getId(),type:type,uri:DriveApp.getFileById(f.getId()).getBlob().getDataAsString()};
  }else{
    throw('Invalid input in saveDataURIInFile.');
  }
}
  • Converting Images to DataURIs Scripts
  • Converting Images to URL's Video
like image 35
Cooper Avatar answered Mar 01 '26 11:03

Cooper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!