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));
}

Reference

 Share!