I'm trying to insert tiff images (and other unsupported formats, e.g. bmps) into google slides from drive using google scripts. I am using the following code:
imageID = '';
slideID = '';
function insertImageFromDrive() {
var image = DriveApp.getFileById(imageID);
var presentation = SlidesApp.openById(slideID);
presentation.getSlides()[0].insertImage(image);
}
but am getting the error 'Exception: The image you are trying to use is invalid or corrupt.' from 'insertImage'.
Is there a workaround or other method for this?
Thanks.
CodePudding user response:
As stated in the .insertImage()
documentation:
Inserting the image fetches it from the BlobSource once and a copy is stored for display inside the presentation. Images must be less than 50MB in size, cannot exceed 25 megapixels, and must be in either in PNG, JPEG, or GIF format.
So TIFF's and BMP's are not supported directly. However, we can convert between some image types using File.getAs()
, which will attempt to convert a file format. As documented:
For images in BMP, GIF, JPEG, or PNG format, any of 'image/bmp', 'image/gif', 'image/jpeg', or 'image/png' are also valid.
So try changing the line in question to
var image = DriveApp.getFileById(imageID).getAs('image/jpeg');
This should work for BMP's but likely won't work for TIFF's. In the case of TIFF's you may have to use some third-party conversion tool.
CodePudding user response:
I believe your goal is as follows.
- You want to retrieve the TIFF and BMP image files and put them to the Google Slides.
Unfortunately, in the current stage, these image files cannot be directly put to the Google Slides. In this case, it is required to convert them to another format that can be put to the Google Slides. In this answer, I would like to introduce this method.
Sample script:
This script uses Drive API. So when you use this script, please enable Drive API at Advanced Google services.
var imageID = "###" // Please set the file ID of the image file.
var imageUrl = Drive.Files.get(imageID).thumbnailLink.replace(/\=s\d /, "=s1000");
var presentation = SlidesApp.openById(slideID);
presentation.getSlides()[0].insertImage(imageUrl);
and also, you can use the following script.
var imageID = "###" // Please set the file ID of the image file.
var imageUrl = Drive.Files.get(imageID).thumbnailLink.replace(/\=s\d /, "=s1000");
var image = UrlFetchApp.fetch(imageUrl).getBlob();
var presentation = SlidesApp.openById(slideID);
presentation.getSlides()[0].insertImage(image);
- When
thumbnailLink
is used by modifying the query parameter, the images of various mimeTypes can be converted to PNG format. This method uses this situation.