google-apps-script - 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;
}
解决方案
这个解决方法怎么样?我认为您的情况有几个答案。因此,请将此视为其中之一。该脚本的流程如下。
- 将图像下载为文件。
- 使用 Drive API 从下载的文件中检索 imageMediaMetadata。
- 删除下载的文件。
- 从 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;
}
推荐阅读
- css - 使用 css 在 div 的底部创建弧
- angular - Angular 在启动其他 Observable 之前等待 Observable 完成
- reactjs - 您可以将“外部”编码的反应应用程序集成到 Visual Studio 项目/工作流中吗?
- sql - 从 Delphi 中的 SQL 查询的输出中复制数据
- ios - 布局约束不起作用iOS swift
- javascript - React 中的双面输入滑块,在达到初始范围 0 后,它也会向左移动并增加值,为什么?
- microsoft-graph-api - 是否有一个 api 端点来列出私人聊天中的文件?
- php - 如何更新存储为行的表列?
- android - 改造导致 Expected BEGIN_OBJECT 但在第 1 行第 153 列路径 $.joining 处为 STRING
- automation - 运行机器人框架脚本时,出现错误:默认适配器失败