Search code examples
google-apps-scriptgoogle-slides

How to insert image into Google slides with [Exception: The image you are trying to use is invalid or corrupt.] error?


The error:

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.

What I have tried

.getBlob()

I tried using DriveApp.getFileById(imgId).getBlob(); instead of DriveApp.getFileById(imgId). But nothing changed.

editing extension vs online converter

I downloaded the photo of the apple from an encyclopedia, which is originally in .webp format. I then tried two things:

  1. I changed its extension from .webp to .jpg by simply editing the filename on my Macbook, and uploaded it to Google Drive. This .jpg generates the same exception.
  2. I uploaded the .webp to an online converter and downloaded the .jpg file, then uploaded it to Google Drive. This .jpg does not generate the exception.

Solution

  • 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?

    Modified script:

    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);
      }
    }
    
    • If you want to modify the size of the image, please modify currentSlide.insertImage(logo) to currentSlide.insertImage(logo).setWidth(###).setHeight(###).