Search code examples
google-apps-scriptgoogle-docsdrive

Save the images from a Google Doc to Google Drive - Google App Script


I am trying to download the images from a Google Doc to my personal Google Drive. I had it up and running for a minute, but once I dropped the working code into a loop to capture all the images in my document, I encountered a bug. The code stopped saving images to my drive and started saving empty files that are 4k in size and decidedly not the .pngs I'm looking for. I'm relatively positive that I have not hit my daily quota, can any of you make sense of this?

Looking forward to your replies.

Here is my non-functioning function:

function imageExtract() {
  var documentName = "googleDoc";
  var wd = DocumentApp.openById("<GOOGLE DOC ID>");

  var imgCount = wd.getBody().getImages().length;                      // get the number of images
  
  for (var i = 0; i < imgCount; i++){
    var images = wd.getBody().getImages()[i].getAs('image/png');       // get the image blob at index 'i'
    var save = DriveApp.createFile((documentName + '-' + i), images);  // name + save the image to drive
    var imgUrl = save.getUrl();

    Logger.log('Saved Image ' + (documentName + '-' + i) + ": " + imgUrl); 
  }
}

Solution

  • Modification points:

    • In your script, I think that DriveApp.createFile((documentName + '-' + i), images) is not correct. In your situation, images is a blob. So in this case, createFile(blob) is required to be used. In the case of createFile(name, content), content is required to be the string type. I thought that this is the reason fo your issue.
    • wd.getBody().getImages() has already been used at outside of for loop. So I think that this can be used in the loop.
    • When the blob is retrieved from wd.getBody().getImages(), the mimeType is image/png as the default.

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

    Modified script:

    function imageExtract() {
      var documentName = "googleDoc";
      var wd = DocumentApp.openById("<GOOGLE DOC ID>");
      var images = wd.getBody().getImages();
      var imgCount = images.length;
      for (var i = 0; i < imgCount; i++){
        var image = images[i].getBlob().setName(documentName + '-' + i);
        var save = DriveApp.createFile(image);
        var imgUrl = save.getUrl();
        Logger.log('Saved Image ' + (documentName + '-' + i) + ": " + imgUrl);
      }
    }
    

    References: