Google Script Image Resizing

2019-07-01 17:55发布

I'm trying to make a script that will resize the images in a google doc. What I have is:

var imgs = currentDoc.getImages();

for (var i = 1; i < imgs.length; i++)
{
   cell = row.insertTableCell(1);
   imgNew = imgs[i].setWidth(365);

   cell.insertImage(1, imgNew.getBlob());
}

The image gets inserted correctly but the size does not change regardless of what I set the width to. Since the image is going into a cell (width=370), is it possible to just make the image take up 100% of the width and scale the height proportionally? If not I can deal with manually setting the number of pixels but that is not working either. Any ideas?

3条回答
Ridiculous、
2楼-- · 2019-07-01 18:19

The problem is that the image size should be changed after it is inserted to a table. The following code works correctly

function test() {
  var doc = DocumentApp.openById('here_is_doc_id');
  var imgs = doc.getImages();
  var table = doc.getTables()[0];
  for (var i = 0; i < imgs.length; i++) {
   var row = table.appendTableRow();
   var cell = row.insertTableCell(0);
   var imgNew = imgs[i].copy();
   cell.insertImage(0, imgNew);
   imgNew.setWidth(365);
  }
}

Please mention, that array indexes, cells numbers, etc. start from 0 and not 1.

查看更多
你好瞎i
3楼-- · 2019-07-01 18:22

Just as an FYI, you don't need to call getBlob()... anything that has a getBlob() can be passed in directly wherever a Blob is needed.

查看更多
疯言疯语
4楼-- · 2019-07-01 18:27

Have you tried:

imgs[i].attr('width', '370');

Or try assigning a class that has width: 100%

查看更多
登录 后发表回答