Reputation: 8386
I am evaluating Google Sheets with AppScripts for a report generator. The requirements include inserting images from Google Drive. One of the input image has a fix format, which I need to crop. ( So the dimensions of the original image and the dimensions of the crop is known.)
I am looking for a solution to achieve this outcome, but I am struggling. I looked into the following methods:
=IMAGE()
functionreplace(imageUrl, crop)
Is there any other workaround? ( Even if it means creating a new file in drive?)
EDIT: Obviously there is the solution to call an external API, or to use GCP services such as CloudFunctions ( which are not free). However I am hoping for an AppScript solution. ( Or using a compatible JS library.)
Upvotes: 3
Views: 1486
Reputation: 201553
I believe your goal as follows.
Unfortunately, in the current stage, there are no methods for directly cropping image using Google Apps Script. This has already been mentioned by your comment. So in this answer, I would like to propose a workaround for cropping image using Google Apps Script.
In this workaround, I use Microsoft Powerpoint and Google Slides. The flow of this workaround is as follows.
By above flow, the cropped image can be retrieved as a blob.
In this sample script, an image is cropped using the parameters using Google Apps Script. In this case, the script reflecting above flow is a bit complicated. So here, I would like to introduce the sample script using a Google Apps Script library. Ref Of course, you can see the whole script there.
Before you use this script, please install ImgApp of the Google Apps Script library. Ref And in this case, please enable Drive API and Slides API at Advanced Google services.
function myFunction() {
const id = "###"; // If you want to crop the image on Google Drive, please set the file ID of the image here.
const object = {blob: DriveApp.getFileById(id).getBlob(), crop: {t: 50, b: 100, l: 200, r: 100}};
const blob = ImgApp.editImage(object);
DriveApp.createFile(blob);
}
crop: {t: 50, b: 100, l: 200, r: 100}
means that the crop size of t
, b
, l
and r
are the top, bottom, left and right, respectively. The unit is pixel.25,000,000 pixels^2
is the maximum size of the image.Upvotes: 4