【问题标题】:Google Apps Script Utilities.base64Decode Exception: Could not decode stringGoogle Apps Script Utilities.base64Decode 异常:无法解码字符串
【发布时间】:2020-05-05 00:02:00
【问题描述】:

我有 base64 编码的 png 图像,它放置在 Google 表格单元格中。需要在 Google App Script 中将其解码为图像并使用以下代码。

================================================ ===============

代码

var ss = SpreadsheetApp.getActiveSheet();
var strBase64Image = ss.getRange('F1').getValue()
ss.getRange('F2').setValue(strBase64Image); // test fn is working
var decodedBytes = Utilities.base64Decode(strBase64Image); // decode to byte array
var blobImg = Utilities.newBlob(decodedBytes, MimeType.PNG); // create blog from byte array
ss.insertImage(blobImg, 6, 3); // write image to F3 cell

================================================ ===============

错误

Exception: Could not decode string.

================================================ ===============

https://codebeautify.org/base64-to-image-converter 中测试时,这个 base64 编码的 png 图像字符串被解码为图像

谢谢, 尼莱什·科德

【问题讨论】:

  • 我可以问你关于你的问题吗? 1.Utilities.base64Decode()的第二个参数是charset。但在您的脚本中,使用了MineType.PNG。而且,在这种情况下,MineType.PNG 会发生错误,因为未定义 MineType。这个怎么样? 2. 使用Utilities.newBlob(decodedBytes, MimeType.PNG) 的blob 名称怎么样? Ref 3. 你的base64数据有表头吗?如果添加了header,请将其删除并重新测试。
  • var decodedBytes = Utilities.base64Decode(strBase64Image, MineType.PNG);是错字,因为我正在尝试所有不同的事情。在邮件中更正为 var decodedBytes = Utilities.base64Decode(strBase64Image);
  • 也尝试直接添加 base64 字符串但得到同样的错误。由于字符限制而不得不截断。代码:var decodedBytes = Utilities.base64Decode("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABC4AAAHvCAYAAACbo54QAAAgAElEQVR4Xu3dUcxu2VkX8D9aE4P........xIVUAAAAASUVORK5CYII=");
  • 你能再次确认我在第一条评论中的第三个问题吗?
  • @Tanaike 感谢您的耐心等待。在以下第三条评论解码成功后,即解码错误消失了。但是现在代码不允许我在工作表上的单元格中插入图像。最后两行代码 ` var blobImg = Utilities.newBlob(decodedBytes, MimeType.PNG); ss.insertImage(blobImg, 6, 3);` 得到错误 Exception: 在对象 SpreadsheetApp.Sheet 上获取方法或属性 insertImage 时出现意外错误。 (第 5 行.

标签: google-apps-script google-sheets


【解决方案1】:

两件事:

  1. 你需要从你的 Base64 字符串中去掉 data:image/png;base64, - 这个标题的存在是什么给你的错误

    Exception: Could not decode string.

  2. 当您create the blob 时,您需要为其命名:var blobImg = Utilities.newBlob(decodedBytes, MimeType.PNG, 'MyImageName'); - 如示例代码 here 中所示。 否则会报错

    Exception: Unexpected error while getting the method or property insertImage on object SpreadsheetApp.Sheet..

【讨论】:

  • 谢谢。您为图像提供名称的建议有助于解决创建 blob 时遇到的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-29
相关资源
最近更新 更多