I am trying to insert images on Google Drive into Google slides using their file ID.
However, I found that for certain images, using either insertImage
or replaceWithImage
generates the [Exception: The image you are trying to use is invalid or corrupt.] error. The following is a small recreation of the problem.
function myfunction() {
var deck = SlidesApp.openById("...");
var slides = deck.getSlides();
var template = slides[0];
var currentSlide = template.duplicate();
var imgId = "...";
var logo = DriveApp.getFileById(imgId);
try {
currentSlide.insertImage(logo);
} catch (err) {
console.log("An error occurred: ", err);
}
}
I cannot find what is wrong with those particular images. They are less than 50MB in size, below 25 megapixels, and in png or jpeg format. Unfortunately I cannot attach the concerned images as they are private photos, and I have yet been able to find a free image that has the same issue. But I will be grateful if anyone gives me any advice on what to try.
I tried using DriveApp.getFileById(imgId).getBlob();
instead of DriveApp.getFileById(imgId)
. But nothing changed.
I downloaded the photo of the apple from an encyclopedia, which is originally in .webp format. I then tried two things:
From I tried using DriveApp.getFileById(imgId).getBlob(); instead of DriveApp.getFileById(imgId). But nothing changed.
, if your file ID of imgId
is the valid value and you can see your image on Google Drive, how about the following modification?
In this modification, the image is converted to PNG. And, the PNG image is put into Google slide.
function myfunction() {
var deck = SlidesApp.openById("...");
var slides = deck.getSlides();
var template = slides[0];
var currentSlide = template.duplicate();
var imgId = "...";
var logo = UrlFetchApp.fetch(`https://drive.google.com/thumbnail?sz=w1000&id=${imgId}`, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob(); // The endpoint is from https://stackoverflow.com/a/31504086
try {
currentSlide.insertImage(logo);
} catch (err) {
console.log("An error occurred: ", err);
}
}
currentSlide.insertImage(logo)
to currentSlide.insertImage(logo).setWidth(###).setHeight(###)
.