How to get the size (in pixels) of a jpeg image I

2019-05-29 23:05发布

问题:

In a script that sends email in HTML format I add an image that is stored in a public shared folder. I get the blob using UrlFetchApp.fetch(photoLink) but the image has not necessarily the right size so in the html code I use width and height attributes (for now with fixed values, see code below) but I'd like it to be automatically resized with the right ratio.

To achieve that I need to know how to get the original size of the image (height and width) but I just don't know how to get it without inserting the image in an intermediate document (which would work but I find this approach a bit weird and unnecessarily complicated... moreover I don't feel like having a useless doc appearing each time I change the image file).

Here is the relevant part of the code that creates the email message :

function sendMail(test,rowData,genTitle,day,title,stHour,endHour){
  var photoLink = sh.getRange('H1').getValue();
  var image = UrlFetchApp.fetch(photoLink);
  //************* find the pixel size of the image to get its ratio
  var msgTemplate = '<A HREF="http://www.domain.be/reservations-global/"><IMG SRC="'+photoLink+'" BORDER=0 ALT="logo" HEIGHT=200 WIDTH=300></A><BR><BR>'+
    'Résumé de vos réservations au nom de <NOM><BR><BR><BR><table style="background-color:lightblue;border-collapse:collapse;" border = 1 cellpadding = 5><th></th><th><TABLEHEADER></th><EVENTS></table><BR><CONCLUSION><BR>Cordialement,<BR><BR>';
  var mailTitle = 'Confirmation de réservation - '+getTextFromHtml(genTitle);
  var descr = '';
  for(var d = 0;d<day.length;++d){
    Logger.log(Number(rowData[(d+5)]));
    var content = '<tr bgcolor="#ffffbb" width="100%"><td><NUMBER> </td><td > <DESCRIPTION></td></tr>'
    if(Number(rowData[(d+5)])>1){var pl = ' places'}else{var pl = ' place'};
    content = content.replace('<NUMBER>',rowData[(d+5)]+pl);
    content = content.replace('<DESCRIPTION>',title[d]+' de '+stHour[d]+' heures à '+endHour[d]+' heures');
    if(Number(rowData[(d+5)])>0){
      descr += content;
    }
  }
  msgTemplate = msgTemplate.replace('<NOM>',rowData[1]).replace('<EVENTS>',descr).replace('<TABLEHEADER>',genTitle); 
  var textVersion = getTextFromHtml(msgTemplate.replace(/<br>/gi,'\n').replace(/<td>/gi,'\n'));
//  Logger.log(textVersion)
  if(test){
    MailApp.sendEmail(Session.getEffectiveUser().getEmail(),mailTitle, textVersion,{'htmlBody':msgTemplate,"replyTo" : retour});
  }
  else
  {
    MailApp.sendEmail(rowData[2],mailTitle, textVersion,{'htmlBody':msgTemplate,"replyTo" : retour});
  }
}

回答1:

There is no easy way within Apps Script to figure out what an image size would be. There are some other projects that might be able to analyze the bitmap data and give you dimensions.

The last time I had to solve this problem. I just wrote a simple App Engine app to do the image math for me -

import webapp2
from google.appengine.api import urlfetch
from google.appengine.api import images
from django.utils import simplejson

class MainHandler(webapp2.RequestHandler):
  def get(self):
    url = self.request.get('url')
    imgResp = urlfetch.fetch(url) #eg. querystring - url=http://xyz.com/img.jpg 
    if imgResp.status_code == 200:
      img = images.Image(imgResp.content);
      jsonResp = {"url":url, "h":img.height, "w":img.width, "format":img.format}
      self.response.headers['Content-Type'] = 'application/json'
      self.response.out.write(simplejson.dumps(jsonResp))

app = webapp2.WSGIApplication([('/imageinfo', MainHandler)], debug=True)

And then I call it from Apps Script like this -

function checkImageSizes() {
  var imageUrls = ['http://developers.google.com/apps-script/images/carousel0.png','http://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg420exif.jpg'];
  for(var i in imageUrls){
    var resp = JSON.parse(UrlFetchApp.fetch('http://arunimageinfo.appspot.com/imageinfo?url='+imageUrls[i]).getContentText());
    Logger.log('Image at %s is %s x %s',resp.url,resp.w,resp.h);
  }  
}

You are welcome to use my App Engine instance if your volume is a couple of times a week :)



回答2:

I doubt you can do this in apps script. Certainly not natively but you might be able to find or adapt a jpg library that looks at the binary blob header and extracts the image size.