Explanation:
Your goal is to retrieve the width
and the height
of the pictures that are stored in a specific folder in Google Drive.
This info is located in imageMediaMetadata in the properties imageMediaMetadata.width
and imageMediaMetadata.height
.
To retrieve this metadata you need to enable the Drive API and pass the fileId
of your file as an argument:
Drive.Files.get(fileId).imageMediaMetadata;
Also store the data in an array and set the values directly to the sheet so you won't have to use appendRow
iteratively which is very inefficient.
Last but not least, it is a good idea to check whether the file is an image
regardless of each extension (jpeg
,png
). Otherwise, you will get an error if you the folder contains other types of files (spreadsheet documents etc.).
You can use includes() to check if the getMimeType contains the word image
:
file.getMimeType().includes("image")
and only for these files, find the width
and height
.
Solution:
function listFolderContents() {
var foldername = 'FolderName1';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername);
var folder = folders.next();
var contents = folder.getFiles();
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
var data = [['name', 'link', 'width', 'height']];
while(contents.hasNext()) {
let file = contents.next();
if( file.getMimeType().includes("image") ){
let name = file.getName();
let link = file.getUrl();
let fileId = file.getId();
let dims = Drive.Files.get(fileId, {supportsAllDrives: true}).imageMediaMetadata
let width = dims.width;
let height = dims.height;
data.push( [name, link, width, height] );
}
}
sheet.getRange(1,1,data.length,data[0].length).setValues(data);
};
Be careful!
Make sure to enable Drive API
from:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…