首页 > 解决方案 > Google Sheets Apps 脚本 > 查找图像比例

问题描述

我正在使用 google sheet 脚本语言,我想从网络链接中获取图像的比例,例如 this flag

我在这里看到了一种方法,但我想从函数中返回比率,而不是把它放在随机单元格中。

到目前为止,我已经设法得到了这个,这似乎不起作用。

function imageSize(imgUrl) {
  if  (typeof imgUrl == 'undefined') {
    imgUrl = 'http://www.google.com/intl/en_ALL/images/logo.gif';
  }
  PropertiesService.getScriptProperties().setProperty('ratio', 0);

  var t = '';     
  t += '<script>\n';
  t += 'function hd(){\n';
  t += 'var img = new Image();\n';
  t += 'img.onload = function() {\n';
  t += "google.script.run.returnVal(this.width / this.height);\n";
  t += '}\n';
  t += "img.src = '" + imgUrl + "';\n";
  t += '}\n';
  t += 'google.script.run.withSuccessHandler(google.script.host.close)\n';
  t += '.returnVal(hd());\n';
  t += '</script>\n';  


  var output = HtmlService.createHtmlOutput(t);
  // output.setSandboxMode(HtmlService.SandboxMode.IFRAME); 
  // SpreadsheetApp.getUi().showModalDialog(output,'please, wait...');
  // output.clear();
  Utilities.sleep(2000);
  return PropertiesService.getScriptProperties().getProperty('ratio');;
}


function returnVal(h) {
  Logger.log(h);
  PropertiesService.getScriptProperties().setProperty('ratio', h);
  return h;
}

标签: google-apps-scriptgoogle-sheets

解决方案


这个解决方法怎么样?我认为您的情况有几个答案。因此,请将此视为其中之一。该脚本的流程如下。

  1. 将图像下载为文件。
  2. 使用 Drive API 从下载的文件中检索 imageMediaMetadata。
  3. 删除下载的文件。
  4. 从 imageMediaMetadata 中检索纵横比。

要使用此示例脚本,请在高级 Google 服务和 API 控制台中启用 Drive API,如下所示。

在高级 Google 服务中启用 Drive API v2

  • 在脚本编辑器上
    • 资源 -> 高级 Google 服务
    • 开启 Drive API v2

在 API 控制台启用 Drive API

  • 在脚本编辑器上
    • 资源 -> 云平台项目
    • 查看 API 控制台
    • 在开始时,单击“探索并启用 API”。
    • 在左侧,单击库。
    • 在搜索 API 和服务中,输入“驱动器”。然后单击 Drive API。
    • 单击启用按钮。
    • 如果 API 已经开启,请不要关闭。

示例脚本

function myFunction(url) {
  var blob = UrlFetchApp.fetch(url).getBlob();
  var fileId = DriveApp.createFile(blob).getId();
  var imageMediaMetadata = Drive.Files.get(fileId).imageMediaMetadata;
  var aspectRatio = imageMediaMetadata.width / imageMediaMetadata.height;
  Drive.Files.remove(fileId);
  return aspectRatio;
}

笔记 :

  • https://www.theodora.com/flags/e_timor.gif您的问题用于此脚本时,1.5将被检索。

参考 :

如果这不是你想要的,我很抱歉。

添加 :

如果您不想在 Google Drive 中创建文件,可以使用此库检索纵横比。该库可以从 blob 中检索图像大小,因为图像的二进制数据已被解析。当此库用于您的情况时,脚本如下所示。

function myFunction(url) {
  var blob = UrlFetchApp.fetch(url).getBlob();
  var res = ImgApp.getSize(blob);
  var aspectRatio = res.width / res.height;
  return aspectRatio;
}

推荐阅读