Resize all images after an edit in google Spreadsh

2019-08-09 07:31发布

问题:

I'm working in a document that imports different images based on a search bar (it sort of automatically generates a flyer with information).

The images however, do not scale nicely so I'm trying google scripts to solve this issue. Without prior knowledge of programming I've managed to come up with the following script but as of now it does exactly nothing :) I hope someone can give me some pointers as to what I'm doing wrong.

Thanks in advance!

function onEdit() {
 
  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var activeSheet =ss.getActiveSheet();
  var images = activeSheet.getImages();
  
  for (var i = 0; i < images.length; i++) {
    
  var originW =  images.getWidth();
  var originH = images.getHeight();
  var newW = originW;
  var newH = originH;
  var ratio = originW/originH
    
  if(originW>maxWidth){
    newW = maxWidth;
    newH = parseInt(newW/ratio);
  }
  
  images.setWidth(newW).setHeight(newH).setAttributes(styleImage);
  var newWW = images.getWidth();
  var newHH = images.getHeight();
  var newRatio = newHH/newWW;
  Logger.log("image width = "+newWW);
  Logger.log("image height = "+newHH);

  if(newHH>maxWidth){
    newHH = maxHeight;
    newWW = parseInt(newHH/newRatio);
  }
  
  images.setWidth(newWW).setHeight(newHH);
  images.getParent().setAttributes(styleImage);
      
  }
}

回答1:

So .getImages() return an array of OverGridImage objects. This means that you will have to run through the array and modify each individual object, which you are almost doing. You have a for loop, but then go on to use the object array instead of selecting the objects within. images ==> images[i] within the for loop.

function onEdit() {

  var app = SpreadsheetApp;
  var ss = app.getActiveSpreadsheet();
  var activeSheet =ss.getActiveSheet();
  var images = activeSheet.getImages();

  for (var i = 0; i < images.length; i++) {

  var originW =  images[i].getWidth();
  var originH = images[i].getHeight();
  var newW = originW;
  var newH = originH;
  var ratio = originW/originH

  if(originW>maxWidth){
    newW = maxWidth;
    newH = parseInt(newW/ratio);
  }

  images[i].setWidth(newW).setHeight(newH).setAttributes(styleImage);
  var newWW = images[i].getWidth();
  var newHH = images[i].getHeight();
  var newRatio = newHH/newWW;
  Logger.log("image width = "+newWW);
  Logger.log("image height = "+newHH);

  if(newHH>maxWidth){
    newHH = maxHeight;
    newWW = parseInt(newHH/newRatio);
  }

  images[i].setWidth(newWW).setHeight(newHH);
  images[i].getParent().setAttributes(styleImage);

  }
}