使用应用程序脚本将图像插入 Google 文档时显示图像数据无效

Inserting image into Google Doc with apps script says invalid image data

我正在尝试将 Google Drive 文件夹中的所有图像插入到 Google 文档中。但是在 insertImage 上我总是得到一个 "invalid image data" 错误。

function myFunction() {
  var folder = DriveApp.getFolderById(id);
  var files = folder.getFiles();
  while (files.hasNext()) {
     var file = files.next();
     var img = file.getBlob();
     var imgDoc = DocumentApp.getActiveDocument().getBody().insertImage(0, img);  
   }
}

有许多示例说明如何执行此操作,并且都说获取图像 blob 并使用它来插入。这段代码中有什么地方给出了不正确的图像斑点吗?

这个答案怎么样?

假设与实验:

根据我的实验,在电子表格中,当 insertImage() in Class Sheet, the limitation is due to the image area (pixels^2) rather than the file size of it. The maximum area of image which can be inserted is 1,048,576 pixels^2.

插入图像时

从这种情况来看,我认为您的问题也与Spreadsheet的情况有关。 insertImage() in Class Body 的限制可能是由于图像区域。于是我做了如下实验

  • 可以插入以下尺寸的图片。

    • 5000 像素 x 5000 像素
    • 25000 像素 x 1000 像素
    • 1000 像素 x 25000 像素
  • 无法插入以下尺寸的图片。

    • 5001 像素 x 5001 像素
    • 5000 像素 x 5001 像素
    • 5001 像素 x 5000 像素

结果发现区域限制为25,000,000像素^2。

关于您的问题:

在您的例子中,共享图像的图像大小为 6240 像素 x 4160 像素。这个区域是 25,958,400 像素^2。该区域大于上述实验检索到的值(25,000,000 像素^2)。至此,认为是错误发生。

解决方法:

为了避免这个限制,这个解决方法怎么样?在此解决方法中,当图像大小超过 25,000,000 像素^2 时,使用驱动器 API 减小图像大小。修改后的脚本如下

修改后的脚本:

function myFunction() {
  var folder = DriveApp.getFolderById(id);
  var files = folder.getFiles();
  while (files.hasNext()) {
     var file = files.next();
     var img = file.getBlob();

     // --- Following script was added.
     var url = "https://www.googleapis.com/drive/v3/files/" + file.getId() + "?fields=imageMediaMetadata(height%2Cwidth)%2CthumbnailLink&access_token=" + ScriptApp.getOAuthToken();
     var res = UrlFetchApp.fetch(url).getContentText();
     var obj = JSON.parse(res);
     if (obj.imageMediaMetadata && (obj.imageMediaMetadata.width * obj.imageMediaMetadata.height) > 25000000) {
       var width = 1000;
       var tlink = obj.thumbnailLink.replace(/=s\d+/, "=s" + width);
       img = UrlFetchApp.fetch(tlink).getBlob();
     }
     // ---

     var imgDoc = DocumentApp.getActiveDocument().getBody().insertImage(0, img);
   }
}
  • 在这个修改中,作为示例,图像尺寸缩小了1000像素的宽度。如果要修改这个,请修改var width = 1000.
  • 我认为在您的脚本中,Drive API 已经自动启用,因为使用了 class DriveApp。但是如果出现与Drive APi相关的错误,请在API控制台检查Drive API是否启用。

参考文献: