Image

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.

Converting All Pages in PDF File to PNG Images using Google Apps Script

Gists

This is a sample script for converting all pages in a PDF file to PNG images using Google Apps Script.

I have already published “Merging Multiple PDF Files as a Single PDF File using Google Apps Script”. In this post, it was found that pdf-lib can be used with Google Apps Script. From this, in this post, I would like to propose a sample script for converting all pages in a PDF file to PNG images using Google Apps Script. This cannot be directly achieved with Google Apps Script. So, I thought that this might be useful for users.

Converting Gmail Message to Image using Google Apps Script

Gists

This is a workaround for converting a Gmail message to a PNG image using Google Apps Script.

Sample script

Please set the message ID of Gmail.

function myFunction() {
  var id = "###"; // Please set your message ID of Gmail.

  var message = GmailApp.getMessageById(id);
  var date = Utilities.formatDate(
    message.getDate(),
    Session.getScriptTimeZone(),
    "yyyy-MM-dd HH:mm:ss"
  );
  var from = message.getFrom();
  var to = message.getTo();
  var subject = message.getSubject();
  var htmlBody = message.getBody();
  var imageBlob = Charts.newTableChart()
    .setDataTable(
      Charts.newDataTable()
        .addColumn(Charts.ColumnType.STRING, "")
        .addRow([`<p style="font-size: 120%">Date: ${date}</p>`])
        .addRow([`<p style="font-size: 120%">From: ${from}</p>`])
        .addRow([`<p style="font-size: 120%">To: ${to}</p>`])
        .addRow([`<p style="font-size: 120%">Subject: ${subject}</p>`])
        .addRow([htmlBody])
        .build()
    )
    .setOption("allowHtml", true)
    .setDimensions(512, 512)
    .build()
    .getBlob();

  DriveApp.createFile(imageBlob.setName("sample.png"));
}
  • In this sample script, the HTML body is used.

Javascript library - CropImageByBorder_js

Javascript Library for Cropping Image by Border

Overview

This is a Javascript library for cropping images by the border.

Description

When an image is used, there is a case where I wanted to simply crop the image by a script. In this Javascript library, the image is cropped by a border. The sample situation is as follows.

In this sample situation, a red rectangle is enclosed by a border (1 pixel) with “#000000”. By this border, this library crops the red rectangle. In this case, the 1-pixel border is not included in the resulting image.

Reducing Image Data Size using Google Apps Script

Gists

This is a sample script for reducing the image data size using Google Apps Script. You might have a situation where you might want to reduce the data size of image data using Google Apps Script. Here, using Google Apps Script, I would like to introduce a sample script for reducing the data size of the image data by reducing the image quality.

Limitations

In the current stage, by the specification of Google side, there are the following limitations.

Report: Images put with IMAGE function on Google Spreadsheet

Gists

This is a report about images put with “=IMAGE(IMAGE_URL)” function on Google Spreadsheet.

Experiment

When “=IMAGE(IMAGE_URL)” is put to a cell “A1” on Spreadsheet, the image is shown in the cell as shown in the following image.

For this situation, when the following script is run,

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
const range = sheet.getRange("A1");
range.copyTo(range, { contentsOnly: true });

The following result is obtained. In this case, the formula is removed and an image can be seen as shown in the following image.

Creating Colorful Buttons on Google Spreadsheet using Google Apps Script

Gists

This is a sample script for creating the colorful buttons on Google Spreadsheet on Google Apps Script.

In order to achieve this, I have been looking for the method for creating the PNG image with the alpha channel using Google Apps Script. Recently, finally, I could find it. By this, the goal of this report got to be able to be achieved by the report of “Creating PNG Image with Alpha Channel using Google Apps Script”.

Creating PNG Image with Alpha Channel using Google Apps Script

This is a sample script for creating a PNG image with the alpha channel using Google Apps Script.

The PNG image with the alpha channel is the image includes the transparent background. I have been looking for the method for creating such image using Google Apps Script. It is considered that when this will be achieved, it will be able to be used for various situations. For example, it is considered the following situations.

Plotting Points on Image using Google Apps Script

Gists

This is a sample script for plotting the points on an image using Google Apps Script.

Unfortunately, in the current stage, there are no methods for directly editing the image and putting the texts and some shapes in the methods for Google Apps Script. So in this case, it is required to use the workaround.

Fortunately, I have already published a report about “Inserting Text on Image using Google Apps Script” in my blog. Ref In this report, this sample is used.

Inserting Text on Image using Google Apps Script

Gists

This is a sample script for inserting a text on an image using Google Apps Script.

Demo

In this demonstration, “sample text” is inserted to the image. The image is from https://www.deviantart.com/k3-studio/art/Rainbow-painting-281090729.

Preparation

When you use this script, please install the following 2 Google Apps Script libraries.

  1. DocsServiceApp
  2. ImgApp

And, please enable Slides API at Advanced Google services.

Flow

The flow of this sample script is as follows.

  1. Retrieve the image size using ImgApp.
  2. Create new Google Slides with the custom page size using DocsServiceApp.
  3. Put the image and text.
  4. Export the result image.

Sample script

function myFunction() {
  const fileId = "###"; // Please set the file ID of image file.

  // Please set the text.
  const text = {
    text: "sample text",
    left: 10,
    top: 120,
    width: 180,
    height: 60,
    fontSize: 30,
  };

  // 1. Retrieve the image size using ImgApp.
  const file = DriveApp.getFileById(fileId);
  const blob = file.getBlob();
  const size = ImgApp.getSize(blob);

  // 2. Create new Google Slides with the custom page size using DocsServiceApp.
  const object = {
    title: "sample title", // Title of created Slides.
    width: { unit: "pixel", size: size.width },
    height: { unit: "pixel", size: size.height },
  };
  const presentationId = DocsServiceApp.createNewSlidesWithPageSize(object);

  // 3. Put the image and text.
  const s = SlidesApp.openById(presentationId);
  const slide = s.getSlides()[0];
  slide.insertImage(blob);
  slide
    .insertTextBox(text.text, text.left, text.top, text.width, text.height)
    .getText()
    .getTextStyle()
    .setFontSize(text.fontSize);
  s.saveAndClose();

  // 4. Export the result image.
  const obj = Slides.Presentations.Pages.getThumbnail(
    presentationId,
    slide.getObjectId(),
    {
      "thumbnailProperties.thumbnailSize": "LARGE",
      "thumbnailProperties.mimeType": "PNG",
    }
  );
  const url = obj.contentUrl.replace(/=s\d+/, "=s" + size.width);
  const resultBlob = UrlFetchApp.fetch(url)
    .getBlob()
    .setName("Result_" + file.getName());
  DriveApp.createFile(resultBlob);
  DriveApp.getFileById(presentationId).setTrashed(true);
}

Note

  • This is a simple sample script. When you want to add more texts and change the text style, please modify the section 3 of above script.
  • In this sample, the maximum size of image is 25,000,000 pixels^2. Ref Please be careful this.

Testing

  • February 6, 2021: When I tested above sample script, I could confirm that the script worked.
  • January 3, 2023: When I tested above sample script, I could confirm that the script worked.

Converting Range in Google Spreadsheet as Image using Google Apps Script

Another approach

10 Aug 2022: Report: Challenging Exporting Selected Cells on Spreadsheet as Image using Google Apps Script and Javascript

Old approach

Gists

This is a sample script for converting a range in Google Spreadsheet as an image data using Google Apps Script. Unfortunately, there are no methods for directly converting the range in Google Spreadsheet as an image data in the built-in functions. So in this case, as a workaround, Charts Service is used.

Decoding QR code on Google Slides using Google Apps Script

Gists

This is a sample script for decoding a QR code put in Google Slides using Google Apps Script. In this case, Javascript is used at the opened dialog. And Canvas API and jsQR are used. So unfortunately, this method cannot be used with the time-driven trigger and the Google Apps Script project of the standalone type.

Of course, this method can be also used for Google Document and Google Spreadsheet. But at Google Spreadsheet, I recommend to retrieve the image of QR code with the fetch method from URL.

Converting SVG Format to PNG Format using Google Apps Script

Gists

This is a sample script for converting the SVG image data to PNG image data using Google Apps Script.

Unfortunately, in the current stage, there are no methods for directly converting the SVG to PNG in Google Drive service. But it can be achieved by Drive API. The sample script is as follows.

Before you use this, please enable Drive API at Advanced Google services.

Sample script

function myFunction() {
  const svgFileId = "###"; // Please set the fileId of the SVG file.

  const url = Drive.Files.get(svgFileId).thumbnailLink.replace(
    "=s220",
    "=s1000"
  );
  const blob = UrlFetchApp.fetch(url).getBlob(); // blob is the image blob of PNG format.

  // In this sample, the retrieved image blob is put to Spreadsheet.
  const sheet = SpreadsheetApp.openById("###").getSheetByName("Sheet1");
  sheet.insertImage(blob, 1, 1).setWidth(500).setHeight(500);
}
  • In this sample script, the converted PNG image is put to the Spreadsheet.

Limitations for Inserting Images to Google Docs

Gists

When an image is inserted to Google Docs (Spreadsheet, Document and Slides) using the method of insertImage using Google Apps Script, there is the case that the error occurs. The error messages are “server error” and “invalid image data”. Here, I would like to introduce the limitations for inserting images to Google Docs. As the result, it was found that the limitation is due to both the mimeTypes and the area of image rather than the file size.

Replacing Text to Image for Google Document using Google Apps Script

Gists

This is a sample script for replacing text to image for Google Document using Google Apps Script (GAS). There is a method for replacing text to text at Class Text of DocumentApp. But there are not methods for replacing text to image. So I created this sample script.

Demo :

This sample image was created by k3-studio.

Usage :

replaceTextToImage(body, replaceText, image, width);
  • body : body of document. You can set by DocumentApp.getActiveDocument().getBody() and DocumentApp.openById(documentId).getBody().
  • replaceText : string you want to replace.
  • image : blob of image you want to replace.
  • width : Width of replaced image. The aspect ratio is constant. The unit is pixels. If you don’t use this, the original size is used.

Script :

In this sample script, all strings of “sample” in the document are replaced to image with the file ID of imageFileId.

Limitation of Images for Inserting to Spreadsheet using Google Apps Script

Gists

Introduction

Here I would like to introduce about the limitation of images for inserting to Spreadsheet using Google Apps Script (GAS). When you want to insert the images to Spreadsheet using GAS, insertImage() of class Sheet is usually used for this situation. At this time, an error sometimes occurs. This indicates that there is the limitation for inserting images to Spreadsheet. So I investigated the limitation.

As a result, it was found that the limitation depends on the image area (pixels^2) rather than the file size of it. The maximum area of image which can be inserted was 1,048,576 pixels^2.

Updated: GAS Library - ImgApp

ImgApp was updated to v1.2.0. New method was added.

3. updateThumbnail()

Overview

This method is for updating thumbnail of files on Google Drive using images you selected.

Description

For example, zip files don’t have the thumbnail on Google Drive. An icon is shown as the thumbnail. For the most files, Google Drive can create automatically each thumbnail. But there are sometimes files which cannot be created the thumbnail. Zip file is also one of them. In order to add and update thumbnails to such files, I added this method.

Retrieving Images on Spreadsheet

Gist

This is a sample script for retrieving images on Spreadsheet.

Unfortunately, there are no methods for retrieving directly images on spreadsheet using GAS. So I use the method which retrieves URL from =image(URL) and retrieves the image from the URL.

In this case, =image(URL) has to be in the cell. Images embedded by insertImage() cannot be retrieved.

At first, please confirm them.

Sample script :

var cell = "A1"; // Cell address with the function of "=image()"
var filename = "samplename"; // Output filename

var image = SpreadsheetApp.getActiveSheet().getRange(cell).getFormula();
var blob = UrlFetchApp.fetch(image.match(/\"(.+)\"/)[1]).getBlob();
DriveApp.createFile(blob.setName(filename));

Flow :

  1. Retrieve =image(URL) using getFormula().
  2. Retrieve URL from =image(URL).
  3. Retrieve file blob using UrlFetchApp.fetch() from the URL.
  4. Output the file blob as a file.

Updated: GAS Library - ImgApp

ImgApp was updated to v1.1.0. New method was added.

2. doResize()

Overview

This method is for resizing images.

Description

Unfortunately, there are no methods to resize images at Google Apps Script. As a workaround, there is a method that it imports the image in Google Document and resizes the image using setWidth() and setHeight(). But in this method, the resized blob cannot be retrieved. So although I had thought of other workaround, I had not been able to find it. Recently, I accidentally discovered the other workaround doResize(). Since it was found that this workaround can be surely used, I added this to ImgApp.

GAS Library - ImgApp - getSize()

1. getSize()

Overview

This method is for retrieving the width and height of image as the unit of pixel.

Description

Unfortunately, there are no methods to directly retrieve the image size at Google Apps Script. As a workaround, there is a method that it imports the image in Google Document and retrieves the size using getWidth() and getHeight(). But in this method, it uses much time and resources on Google. So I thought of retrieving the information of image at the binary level, and created this. By this, the low process cost could be achieved.

GAS Library - CreateImg

Recently, I had been looking for creating an image from coordinate data. Unfortunately I have never found them. So I made this. This Google Apps Script (GAS) library creates an image file from coordinate data.

You can see the detail information at https://github.com/tanaikech/CreateImg.

There is a part where I would like to improve in this library. That’s convByteSlice(). I think that there is the method to be faster about the part. If you know much about the logical operation using GAS, if you teach me about the improvements. I’m so glad.