Converting Various Formatted Images to PNG Format and JPEG format using Google Apps Script

Gists

This is a sample script for converting various images to PNG Format and JPEG format using Google Apps Script.

The flow of this sample script is as follows.

  1. Convert the file to PNG format by the thumbnail link.
  2. Convert PNG format to JPEG format if outputFormat is “JPEG”.
  3. Create the image data in the JPEG format in the root folder as a file.

Sample script

Please set your file ID and output format.

function myFunction() {
  const fileId = "###"; // Please set the file ID of the image file and the movie file.
  const outputFormat = "JPEG"; // "PNG" or "JPEG".

  const file = DriveApp.getFileById(fileId);
  const url = `https://drive.google.com/thumbnail?id=${fileId}&sz=w1000`;
  let blob = UrlFetchApp.fetch(url, {
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
  }).getBlob();
  let name = file.getName().split(".")[0] + ".png";
  if (outputFormat == "JPEG") {
    blob = blob.getAs("image/jpeg");
    name = name.replace(".png", ".jpg");
  }
  DriveApp.createFile(blob.setName(name));
}
  • When this script is run, the thumbnail of the file is converted to PNG or JPEG format and saved as an image file to the root folder.

  • When this script is used, not only image files but also movie files, Google Docs (Document, Spreadsheet, Slides), PDF, and so on, all files which have thumbnail images can be converted to PNG format or JPEG format.

  • If you want to create a file for the specific folder, please modify it as follows.

    • From

      DriveApp.createFile(blob.setName(name));
      
    • To

      DriveApp.getFolderById("###folderId###").createFile(blob.setName(name));
      

Reference

 Share!