0

I'm writing an Google Docs add-on. What it does: It takes images out of a Google Drive folder and places it in a Google Doc. ... Well, that's what it does in a nutshell ;-)

I wonder if there is a way to find out the image orientation (landscape/portrait) BEFORE inserting it in the Google Doc. (Once it is inserted, it is not a problem, but I need to figure it out BEFORE the image is inserted so the script runs faster.)

So what I need is something like this:

function getImagesFromFolder(ID){

DriveApp.getFolderById(ID).getFiles();
var mimetypes = ["image/png","image/jpeg","image/gif","image/bmp"];
var images = [];
while (files.hasNext())
{
 var file = files.next();
 if( mimetypes.indexOf(file.getMimeType()) != -1) 
  {
   var imageObject = {};
   imageObject.fileAsJpeg = file.getBlob().getAs("image/jpeg")
   imageObject.orientation = getImagefileOrientation(file) 

//Here is the issue! I need a 'getImageFileOrientation-function' that returns 'landscape' or 'portrait'

   images.push(imageObject); 
  }
}
return images;
}



 //------Later on I will be using----------
    for (var i = 0;i<images.length;i++)
    {
     if (images[i].orientation == 'portrait')
      {
      // some code that rotates the image when it is inserted in the Google Doc. Not the problem.
      }
      else
      {
       googleDocBody.insertImage(images[i].fileAsJpeg); //Not the problem
      }
    }

Thanks in advance!

Jasper

Jasper Cuvelier
  • 503
  • 6
  • 14
  • 1
    The `.getWidth` and `.getHeight` functions associated with an Image in Docs, Forms and Sheets are available after inserting them. Have you tried inserting them into an empty Doc to get at these attributes and then discarding? Is that any quicker? – JSDBroughton Apr 30 '16 at 05:27
  • [Mogsdad's answer](http://stackoverflow.com/questions/30582284/how-to-extract-exif-data-from-jpeg-files-in-drive) should help – Adelin Apr 30 '16 at 10:53
  • @Adelin: that looks really helpfull indeed! – Jasper Cuvelier Apr 30 '16 at 10:59
  • @JasperCuvelier cool - you can give the guy an upvote :) – Adelin Apr 30 '16 at 11:01

1 Answers1

1

Technically the answer is yes you can, but the actual code for doing so is too long for SO as the method for doing so from Blob varies by image type.

The bitcode header for most images stores dimensions and from there it's a simple math question to determine aspect. The headers that record this is where it is different per type.

If inserting them into an empty dummy doc and using getWidth and getHeight is not quick enough for you, then using UrlFetch to 3rd party APIs us also going to be Roos slow.

In which case I'd recommend looking at porting image-size, which is a node.js library, into your Apps Script or maybe make it as a separate library. The node library includes functions for handling image in a stream, but you could drill downtown just wrapping the detect and calculate methods.

JSDBroughton
  • 3,966
  • 4
  • 32
  • 52