Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing image in Google Apps Script

I have an image and I want to resize this.

App Script code:

var fileId = 'idImage';
var img = DriveApp.getFileById(fileId).getBlob().;
newFile.getBody().insertImage(0, img); 

Object Blob can't resize so how can I resize my image?

Regards

like image 326
Hann Avatar asked Apr 23 '14 09:04

Hann


People also ask

How do I resize an image in Google script?

Resize an image in Google SheetsPress and hold your left mouse button on one of the squares on the edge or corner of the image. While still pressing the mouse button, drag the mouse towards the image to decrease its size, or drag away from the image to increase its size.

How do I add an image to a Google script?

To add an image to a cell, highlight the cell and click F2 to enter the formula mode. Next, enter the formula =IMAGE("URL") where URL is the public web address of that image.


1 Answers

I've tried the solution you gave, but no success, I always get a bizarre image ratio. I've found a working solution in this frightening post (I am a newbie):

Quite exact code :

var inlineI = GDoc.appendImage(img);
var width = inlineI.getWidth();
var newW = width;
var height = inlineI.getHeight();
var newH = height;
var ratio = width/height

if(width>640){
newW = 640;
newH = parseInt(newW/ratio);
}
inlineI.setWidth(newW).setHeight(newH)

The thing to do is to insert the image as blob (as usual), and THEN get its dimensions, within the doc to calculate the ratio, and FINALLY set its dimensions. Hope it helps !

btw, thanks @serge-insas !

EDIT : this is an updated version of the above code, to also fix the height of the picture. There might be some weird stuff for specialists, but as said, I'm a noob !

if(insertImage == true){
  var cellImage = ligne.appendTableCell().insertImage(0, image);
  //get the dimensions of the image AFTER having inserted it to fix
  //its dimensions afterwards
  var originW =  cellImage.getWidth();
  var originH = cellImage.getHeight();
  var newW = originW;
  var newH = originH;
  var ratio = originW/originH

  if(originW>maxWidth){
    newW = maxWidth;
    newH = parseInt(newW/ratio);
  }
  cellImage.setWidth(newW).setHeight(newH).setAttributes(styleImage);
  var newWW = cellImage.getWidth();
  var newHH = cellImage.getHeight();
  var newRatio = newHH/newWW;
  Logger.log("image width = "+newWW);
  Logger.log("image height = "+newHH);

  if(newHH>maxWidth){
    newHH = maxHeight;
    newWW = parseInt(newHH/newRatio);
  }
  cellImage.setWidth(newWW).setHeight(newHH);
  cellImage.getParent().setAttributes(styleImage);
like image 62
Romain Avatar answered Oct 09 '22 02:10

Romain