Search code examples
javascriptgoogle-apps-scriptblobpng

Downloaded image from Blob Data not a proper PNG file


I have been hacking together data and scripts from lots of posts and I finally got something that is SO close to working, but I am having an issue on the home straight....

I am using the dom-to-image library to turn my Container div in to a blob so that I can save to my google drive

Javascript:

btn.onclick = function() {
      domtoimage.toPng(document.getElementById('app')).then(function (dataUrl)
      {
         base64 = dataUrl.replace(/^.*,/, "");
         console.log(base64);
         google.script.run.withSuccessHandler(e => console.log(e)).saveFile(dataUrl); 
      });
}

And this generates a string that when I check it with https://codebeautify.org/base64-to-image-converter it looks correct and I can download that image as a PNG is all good.... BUT....

Then I send it to my GS function:

function saveFile(e) {
    var blob = Utilities.newBlob(e, MimeType.PNG, "layout.png");
    DriveApp.createFile(blob);
    return "Done.";
}

And this seems to work, in that it creates an "image" file on my google drive that is similar size to the downloaded test image from Code Beautify...

However, google will not preview it and when I downloaded it Photoshop says its not a PNG file and any other image program wont read it either :(

Where am I going wrong? Is it the MimeType syntax? (I have tried a few). Is it raw blob data? Help?


Solution

  • In your script, I think that there are 2 modification points.

    Modification points:

    1. At HTML&Javascript side, base64 of base64 = dataUrl.replace(/^.*,/, "") is not used with google.script.run.withSuccessHandler(e => console.log(e)).saveFile(dataUrl).
    2. At Google Apps Script side, the base64 data is not decoded.

    When above points are reflected to your script, it becomes as follows.

    Modified script:

    HTML&Javascript side:
    btn.onclick = function() {
          domtoimage.toPng(document.getElementById('app')).then(function (dataUrl)
          {
             base64 = dataUrl.replace(/^.*,/, "");
             console.log(base64);
             google.script.run.withSuccessHandler(e => console.log(e)).saveFile(base64);  // Modified
          });
    }
    
    Google Apps Script side:
    function saveFile(e) {
      var bytes = Utilities.base64Decode(e);  // Added
      var blob = Utilities.newBlob(bytes, MimeType.PNG, "layout.png");  // Modified
      DriveApp.createFile(blob);
      return "Done.";
    }
    

    References: