How to check the resolution of the image - google-apps-script

How to check the resolution of the image which is stored on Google Drive using Google Apps Script.
var childFile = files.next();
data = [
childFile.getName(),
childFile.getDateCreated(),
childFile.getUrl(),
childFile.getLastUpdated(),
childFile.getDescription(),
childFile.getSize()
];
In the above code I am able to get the size of the image but how can I get the resolution of image.

You can use the Google Drive API to get the image size and other EXIF data. Make sure you have enabled Drive API under the Developer Console for the Apps Script project.
function getImageSize(fileID) {
var api = "https://www.googleapis.com/drive/v2/files/" + fileID;
var meta = JSON.parse(UrlFetchApp.fetch(api, {
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken()
}
}).getContentText());
Logger.log(meta.imageMediaMetadata.height);
Logger.log(meta.imageMediaMetadata.width);
}

Related

Google Slides to PNG with Apps Script [duplicate]

Good Morning All. I have written a short script which batch-creates [single page] Google Slides based on rows from a spreadsheet. While in the loop for each creation, I would like to create a PNG of the Slide in Google Drive (or download on the user's desktop). These pictures should be the same specs as if a user clicked File>Download>PNG - the heavy small text requires full projector HD - so I don't believe I can use the "Thumbnail" function which appears limited to 1600 pixels.
My code below generates the error "Converting from text/html to image/png is not supported" - so I'm not sure if this is a limitation of the API or a problem with my coding. Thank you in advance.
var options =
{
"contentType" : "image/PNG"
};
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/PNG';
var response = UrlFetchApp.fetch(url, options);
var image = response.getAs(MimeType.PNG);
image.setName(SlideName);
DriveApp.createFile(image);
Yes, It is possible.
You can use Google slide API and make a PNG file of every page of Google slide.
Here is the code,
BUT first you have to enable API as following
open script editor
click on resources-> Advanced Google Services
Enable Google slide API and Drive API .
click on ok
now copy and paste this code,
and write your slide ID in presentationID.
function generateScreenshots() {
var presentationId = "***ADD YOUR Google Slide ID Only***";
var presentation = SlidesApp.openById(presentationId);
var baseUrl =
"https://slides.googleapis.com/v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail";
var parameters = {
method: "GET",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
contentType: "application/json",
muteHttpExceptions: true
};
// Log URL of the main thumbnail of the deck
Logger.log(Drive.Files.get(presentationId).thumbnailLink);
// For storing the screenshot image URLs
var screenshots = [];
var slides = presentation.getSlides().forEach(function(slide, index) {
var url = baseUrl
.replace("{presentationId}", presentationId)
.replace("{pageObjectId}", slide.getObjectId());
var response = JSON.parse(UrlFetchApp.fetch(url, parameters));
// Upload Googel Slide image to Google Drive
var blob = UrlFetchApp.fetch(response.contentUrl).getBlob();
DriveApp.createFile(blob).setName("Image " + (index + 1) + ".png");
screenshots.push(response.contentUrl);
});
return screenshots;
}
This answer is outdated, leaving up for documentation purposes but please see other answer.
Answer:
Unfortunately it is not possible to export a Slides as a PNG file using the the Slides nor Drive APIs.
More Information:
According to the documentation, there are only four available MimeTypes for exporting Presentations files:
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.oasis.opendocument.presentation
application/pdf
text/plain
Attempting to export to the image/png MIME Type results in the following error:
Converting from text/html to image/png is not supported
For testing purposes, I tried using the /export/pdf endpoint and making a second conversion to PNG from there like so:
function slidesAsPngAttempt() {
var presentationCopyId = "1Loa...pQs";
var options =
{
"contentType" : "application/pdf"
};
// for exporting to pdf the /export/pdf needs to be all lower case to avoid 404
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/pdf';
var response = UrlFetchApp.fetch(url, options);
var pdfAsblob = response.getBlob();
var image = pdfAsblob.getAs('image/png');
image.setName(DriveApp.getFileById(presentationCopyId).getName());
DriveApp.createFile(image);
}
Unfortunately, a similar error occurs when running var image = pdfAsblob.getAs('image/png'):
Converting from application/pdf to image/png is not supported.
From the same export MIME types reference documentation, the only export types available for PDF files are:
text/csv
text/tab-separated-values
application/zip
References:
G Suite documents and corresponding export MIME types
Google Apps Script - method Blob.getAs(contentType)

using youtube API with Google Apps Scripts

I am not able to test my scripts.
If you can help with the code here - it is not working
As per documentation - https://developers.google.com/youtube/v3/docs/videos/insert
if (serviceYT.hasAccess()) {
url = 'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&mine=true&key='+ API_KEY;
var data;
data = '{"snippet":{"title":"testtitle","description":"testdes","categoryId":"19","tags":["asdf","sadfds"]},"status":{"privacyStatus":"public"}}';
var options = {
'headers': {
'Authorization': 'Bearer ' + serviceYT.getAccessToken()
,'Accept': 'application/json'
},
'contentType': 'application/json',
'method' : 'POST',
'payload' : data,
'muteHttpExceptions' : true
};
//execute and handle the response
var response = UrlFetchApp.fetch(url, options);
var responseCode = response.getResponseCode();
var result = JSON.parse(response.getContentText());
Logger.log(result);
}
My questions -
where to put the video?
Resolution of the error I am getting:
{error={message='status', code=400.0, errors=[{reason=unexpectedPart, domain=youtube.part, message='status', location=part, locationType=parameter}]}}
A youtube object (a empty video basically) is successfully added to the youtube which is visible via studio. its a empty video but the title, description, status etc... other things are correcty setup.
Any ideas on how to add the media or video??
Where in the payload the video blob has to be added?
I am not able to get it in the documentation.
https://developers.google.com/youtube/v3/docs/videos/insert
I believe your goal is as follows.
You want to upload a movie file to your YouTube channel with the title, description, and so on.
The movie file is put in your Google Drive.
You want to achieve this by directly requesting to the endpoint using UrlFetchApp.
In this case, how about the following modified script?
Modified script:
Before you use this script, please enable YouTube Data API v3 and add the scope of https://www.googleapis.com/auth/youtube. And please set the file ID of the movie file in your Google Drive to const fileId = "###";.
serviceYT.getAccessToken() is from your script.
function myFunction() {
const fileId = "###"; // Please set the file ID of movie file on the Google Drive.
const metadata = {
"snippet": { "title": "testtitle", "description": "testdes", "categoryId": "19", "tags": ["asdf", "sadfds"] },
"status": { "privacyStatus": "public" }
};
const url = 'https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus';
const file = DriveApp.getFileById(fileId);
const boundary = "xxxxxxxxxx";
let data = "--" + boundary + "\r\n";
data += "Content-Type: application/json; charset=UTF-8\r\n\r\n";
data += JSON.stringify(metadata) + "\r\n";
data += "--" + boundary + "\r\n";
data += "Content-Type: " + file.getMimeType() + "\r\n\r\n";
const payload = Utilities.newBlob(data).getBytes().concat(file.getBlob().getBytes()).concat(Utilities.newBlob("\r\n--" + boundary + "--").getBytes());
const options = {
method: "post",
contentType: "multipart/form-data; boundary=" + boundary,
payload: payload,
headers: { 'Authorization': 'Bearer ' + serviceYT.getAccessToken() },
muteHttpExceptions: true,
};
const res = UrlFetchApp.fetch(url, options).getContentText();
console.log(res);
}
In your script, you are using the endpoint of url = 'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&mine=true&key='+ API_KEY;. Your data has the properties of snippet and status. In this case, it is required to use the endpoint of https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus.
In order to upload the movie file, it is required to request with multipart/form-data.
When this script is run, the movie file on Google Drive is uploaded to YouTube.
Note:
In the current stage, even when "privacyStatus": "public" is used, the uploaded video is not public. About this, you can see it at the official document as follows. Ref
All videos uploaded via the videos.insert endpoint from unverified API projects created after 28 July 2020 will be restricted to private viewing mode. To lift this restriction, each API project must undergo an audit to verify compliance with the Terms of Service. Please see the API Revision History for more details.
When you use the YouTube API at Advanced Google services, you can use the following simple script. Ref
function myFunction2() {
const fileId = "###"; // Please set the file ID of movie file on the Google Drive.
const res = YouTube.Videos.insert({
"snippet": { "title": "testtitle", "description": "testdes", "categoryId": "19", "tags": ["asdf", "sadfds"] },
"status": { "privacyStatus": "public" }
}, ["snippet", "status"], DriveApp.getFileById(fileId).getBlob());
console.log(res);
}
References:
Videos: insert
Multipart-POST Request Using Google Apps Script
fetch(url, params)

How to get video duration of google drive file via API?

On my website, I am hosting a few videos via Google Drive. On my sidebar, there is a thumbnail of the videos and I'd like to show the duration of the video in the corner. I have looked at two similar questions (here and here) to solve this problem. This is what I produced from looking at these two problems:
function sample1() {
console.log("running script");
var fileId = "theFileID"; // Please set the file ID of the video file.
var fields = "mimeType,name,videoMediaMetadata"; // duration is included in "videoMediaMetadata"
var url = "https://www.googleapis.com/drive/v3/files/" + fileId + "?fields=" + encodeURIComponent(fields) + "&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
var obj = JSON.parse(res);
console.log("filename: %s, duration: %s seconds", obj.name, obj.videoMediaMetadata.durationMillis / 1000);
}
sample1();
However, when I check the console after running this script, nothing is printed after "running script". Is there a different approach I should be taking in my program when attempting to solve this problem via Google APIs?
Using the Drive API method Files: get with Apps Script I have been able to get the durationMillis from the video.
You have to add the Drive API Advanced Services on the Apps Script project:
function getVideoLength() {
var fileId = "FILE ID";
var returnedFile = Drive.Files.get(fileId);
Logger.log(returnedFile.videoMediaMetadata.durationMillis)
}

Google Suite - Apps Script - Download Slides as PNG files via API

Good Morning All. I have written a short script which batch-creates [single page] Google Slides based on rows from a spreadsheet. While in the loop for each creation, I would like to create a PNG of the Slide in Google Drive (or download on the user's desktop). These pictures should be the same specs as if a user clicked File>Download>PNG - the heavy small text requires full projector HD - so I don't believe I can use the "Thumbnail" function which appears limited to 1600 pixels.
My code below generates the error "Converting from text/html to image/png is not supported" - so I'm not sure if this is a limitation of the API or a problem with my coding. Thank you in advance.
var options =
{
"contentType" : "image/PNG"
};
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/PNG';
var response = UrlFetchApp.fetch(url, options);
var image = response.getAs(MimeType.PNG);
image.setName(SlideName);
DriveApp.createFile(image);
Yes, It is possible.
You can use Google slide API and make a PNG file of every page of Google slide.
Here is the code,
BUT first you have to enable API as following
open script editor
click on resources-> Advanced Google Services
Enable Google slide API and Drive API .
click on ok
now copy and paste this code,
and write your slide ID in presentationID.
function generateScreenshots() {
var presentationId = "***ADD YOUR Google Slide ID Only***";
var presentation = SlidesApp.openById(presentationId);
var baseUrl =
"https://slides.googleapis.com/v1/presentations/{presentationId}/pages/{pageObjectId}/thumbnail";
var parameters = {
method: "GET",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
contentType: "application/json",
muteHttpExceptions: true
};
// Log URL of the main thumbnail of the deck
Logger.log(Drive.Files.get(presentationId).thumbnailLink);
// For storing the screenshot image URLs
var screenshots = [];
var slides = presentation.getSlides().forEach(function(slide, index) {
var url = baseUrl
.replace("{presentationId}", presentationId)
.replace("{pageObjectId}", slide.getObjectId());
var response = JSON.parse(UrlFetchApp.fetch(url, parameters));
// Upload Googel Slide image to Google Drive
var blob = UrlFetchApp.fetch(response.contentUrl).getBlob();
DriveApp.createFile(blob).setName("Image " + (index + 1) + ".png");
screenshots.push(response.contentUrl);
});
return screenshots;
}
This answer is outdated, leaving up for documentation purposes but please see other answer.
Answer:
Unfortunately it is not possible to export a Slides as a PNG file using the the Slides nor Drive APIs.
More Information:
According to the documentation, there are only four available MimeTypes for exporting Presentations files:
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/vnd.oasis.opendocument.presentation
application/pdf
text/plain
Attempting to export to the image/png MIME Type results in the following error:
Converting from text/html to image/png is not supported
For testing purposes, I tried using the /export/pdf endpoint and making a second conversion to PNG from there like so:
function slidesAsPngAttempt() {
var presentationCopyId = "1Loa...pQs";
var options =
{
"contentType" : "application/pdf"
};
// for exporting to pdf the /export/pdf needs to be all lower case to avoid 404
var url = 'https://docs.google.com/presentation/d/' + presentationCopyId + '/export/pdf';
var response = UrlFetchApp.fetch(url, options);
var pdfAsblob = response.getBlob();
var image = pdfAsblob.getAs('image/png');
image.setName(DriveApp.getFileById(presentationCopyId).getName());
DriveApp.createFile(image);
}
Unfortunately, a similar error occurs when running var image = pdfAsblob.getAs('image/png'):
Converting from application/pdf to image/png is not supported.
From the same export MIME types reference documentation, the only export types available for PDF files are:
text/csv
text/tab-separated-values
application/zip
References:
G Suite documents and corresponding export MIME types
Google Apps Script - method Blob.getAs(contentType)

Is it possible to use Google Apps Script to save a doc as epub?

I know that it is possible to convert a Google Doc file to pdf using Google Apps Script.
Is there a similar syntax like the one below that works for epub?
docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
This code will convert your document and save it in your Drive root folder.
function convert(fileId) {
var link = Drive.Files.get(fileId).exportLinks["application/epub+zip"];
var response = UrlFetchApp.fetch(exportLink, {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
}
});
DriveApp.createFile(response.getBlob()).setName("file.epub");
}