I'm trying to decode the dataURI to Image. I use split() to cut the "data:image/png;base64,",but it will let my variable cannot be decoded
function Image_Build() {
var data_sheet = SpreadsheetApp.openById('10DY3Qlw6EwC_NnxSxoU-0H88PYKv83rOaRImn4yubDc').getSheetByName('表單回應 1');
var data_col = data_sheet.getLastColumn();
var data_row = data_sheet.getLastRow();
var range = data_sheet.getRange(1,1,data_row,data_col);
var values = range.getValues();
var datauri = values[1][16];
console.log(datauri);
datauri = datauri.split("data:image/png;base64,")
console.log(datauri);
datauri = Utilities.newBlob(datauri);
dataurl = Utilities.base64Decode(dataurl);
var folder = DriveApp.getFolderById("1yECMj1EvBQhV1gigslYJu5KM3bxsK9yy");
var img;
folder.createFile("test", datauri, 'image/png');
}
.
CodePudding user response:
The reason for the message is that split()
returns an array with multiple strings using the delimiter that you defined, so after datauri = datauri.split("data:image/png;base64,")
, the result is an array like this:
['', '<yourbase64string>']
So when trying to create the Blob you have to use datauri[1]
. Also, after that you mistyped datauri
as dataurl
when trying to use base64Decode
, which you also need to fix. And also remember to use base64Decode
before creating the blob, not after.
Even after fixing that I had some issues while testing to convert a dataURI. It turns out that createFile(name, content, mimeType)
, is supposed to take a string as content
, not a blob. Instead you have to use createFile(blob)
.
The difference is just the number of parameters that you need to use, but that also means that you'll have to specify the mimeType and filename when using newBlob()
. Here's a sample I built based on your current code that was able to successfully convert a dataURI string:
function Image_Build() {
var data_sheet = SpreadsheetApp.openById('10DY3Qlw6EwC_NnxSxoU-0H88PYKv83rOaRImn4yubDc').getSheetByName('表單回應 1');
var data_col = data_sheet.getLastColumn();
var data_row = data_sheet.getLastRow();
var range = data_sheet.getRange(1,1,data_row,data_col);
var values = range.getValues();
var datauri = values[1][16];
datauri = datauri.split("data:image/png;base64,")
datauri = Utilities.base64Decode(datauri[1]); //use datauri[1] because [0] is a blank string
datauri = Utilities.newBlob(datauri, 'image/png', 'test.png'); //define the name and mymetype when creating the blob
var folder = DriveApp.getFolderById("1yECMj1EvBQhV1gigslYJu5KM3bxsK9yy");
folder.createFile(datauri);
}