=具有指定高度和自动宽度的IMAGE(" url")以保持纵横比

时间:2016-02-26 14:59:52

标签: google-sheets formulas

我有一列不同宽高比的图像网址,我使用= IMAGE(" url")将它们转换为图像,但希望它们在保持时都具有指定的高度纵横比。

我想在行之间留出一些空白区域,即:它们的高度会比图像高度稍大,所以第一个选项没有帮助,我不知道如何使用" auto"宽度使用选项4。

1 个答案:

答案 0 :(得分:1)

使用脚本和公式

一种可能的方法是使用脚本:

  1. 借助脚本
  2. 查找width / height
  3. 使用简单的image功能
  4. 我没有找到一种简单的方法来获取谷歌表脚本中的图像大小。因此,此解决方案不能用于自定义公式。运行脚本的唯一方法是直接执行,或将其分配给按钮。看一下例子:

    enter image description here

    在我的example file中,您可以将图片的网址粘贴到A列,然后点击图片(按钮)刷新width / height参数。这需要一些时间,具体取决于图片的数量。

    单元格C2中的公式为: =IMAGE(A2,4,26,26*B2)

    如果你愿意,你也可以把它变成一个arrayFormula,使用: =ArrayFormula(IMAGE(A2:A11,4,26,26*B2:B11))

    在我的情况下,26号是图片的正确高度,根据您的需要进行更改。

    必填代码:

    function returnDims(){
      var sheet = SpreadsheetApp.getActiveSheet();
      var lRow = sheet.getLastRow();
      var imgUrl = '';
      
      for (var i = 2; i <= lRow; i++) {
        r1 = sheet.getRange(i, 1);
        imgUrl = r1.getValue();
        if (imgUrl != ''){
          imageSize(imgUrl, i, 2);
          Utilities.sleep(2000);
        }
      }
    }
    
    
    function imageSize(imgUrl, r, c) {
      if  (typeof imgUrl == 'undefined') {
        imgUrl = 'http://www.google.com/intl/en_ALL/images/logo.gif';
      }
      
      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, " + r + ", " + c + ");\n";
      t += '}\n';
      t += "img.src = '" + imgUrl + "';\n";
      t += '}\n';
      t += 'google.script.run.withSuccessHandler(google.script.host.close)\n';
      t += '.returnVal(hd(), ' + r + ', ' + c + ');\n';
      t += '</script>\n';  
      
      
      var output = HtmlService.createHtmlOutput(t);
      output.setSandboxMode(HtmlService.SandboxMode.IFRAME); 
      SpreadsheetApp.getUi().showModalDialog(output,'please, wait...');
      output.clear();
      
    }
    
    
    function returnVal(h, r, c) {
      Logger.log(h);
      var sheet = SpreadsheetApp.getActiveSheet();
      var R = sheet.getRange(r, c);
    
      if (h != '') {
      R.setValue(h);}
    
    }

    如果您的图片很大,则可能需要在此代码中增加暂停:Utilities.sleep(2000);更大的数字。

    <强> Referencies

    我借用了一些好的代码:

    希望它有所帮助并等待更好的解决方案!