[英]Google Apps Scripts: InsertImage() function isn't working
I'm trying to paste png images from my drive into a spreadsheet.我正在尝试将驱动器中的 png 图像粘贴到电子表格中。 Lots of articles say that insertImage()
on Sheet Class will achieve this but when I run the code below, I keep getting a Service error where insertImage() is called.很多文章都说 Sheet Class 上的insertImage()
可以实现这一点,但是当我运行下面的代码时,我不断收到调用 insertImage() 的服务错误。 I googled it and looked it up here as well but haven't been able to find the solution yet.我在谷歌上搜索并在这里查找,但还没有找到解决方案。 What am I doing it wrong?我做错了什么?
function pastePhotosFromDrive(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("画像");
var folderId = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
var files = DriveApp.getFolderById(folderId).getFiles();
var row = 1;
var col = 1;
Logger.log(files);
// var file1 = files.next();
// var blob1 = file1.getBlob());
while(files.hasNext()){
var file = files.next();
var blob = file.getBlob();
sheet.insertImage(blob, col, row);
row += 3;
if(row >= 25){
col = 0;
row += 20;
}
}
}
How about this answer?这个答案怎么样?
I thought that in your situation, it is considered that the following 2 situations might occur.我认为在你的情况下,认为可能会出现以下2种情况。
As one of several workarounds, I would like to propose to modify the size of the image by selecting the image file.作为几种解决方法之一,我想建议通过选择图像文件来修改图像的大小。
When your script is modified, please modify as follows.当您的脚本被修改时,请进行如下修改。
Before you use this script, please enable Drive API at Advanced Google Services .在您使用此脚本之前, 请在 Advanced Google Services 中启用 Drive API 。
while(files.hasNext()){
var file = files.next();
var blob = file.getBlob();
sheet.insertImage(blob, col, row);
row += 3;
if(row >= 25){
col = 0;
row += 20;
}
}
while(files.hasNext()){
var file = files.next();
if (file.getMimeType().indexOf("image") > -1) { // Here, the image file is selected.
var blob;
var obj = Drive.Files.get(file.getId());
var imageMetadata = obj.imageMediaMetadata;
if (imageMetadata.height * imageMetadata.width > 1048576) {
var width = 500; // Here, as a test case, 500 pixels is used for the width.
var tlink = obj.thumbnailLink.replace(/=s\d+/, "=s" + width);
blob = UrlFetchApp.fetch(tlink).getBlob();
} else {
blob = file.getBlob();
}
sheet.insertImage(blob, col, row);
row += 3;
if(row >= 25){
col = 0;
row += 20;
}
}
}
If I misunderstood your question and this was not the result you want, I apologize.如果我误解了您的问题并且这不是您想要的结果,我深表歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.