In Google Apps Script, I am using the AdminDirectory Api to get a user photo from the admin console.
The returned object shoud have a string containing the photo encoded as base64, but I can only get an object of numbers.
function hentSkolefoto() {
var photo = AdminDirectory.Users.Photos.get("[email protected]");
Logger.log(typeof(photo.photoData));
Logger.log(photo.photoData.toString());
}
The log output says:
object
Logging output too large. Truncating output. [-1.0, -40.0, -1.0, -32.0, 0.0, 16.0,...
How do I decode and - ultimately - show the photo on a web page?
I have tried to add "toString()":
Logger.log(photo.photoData.toString())
Log output:
Logging output too large. Truncating output. -1,-40,-1,-32,0,16,...
I have also tried to decode as suggested here.
CodePudding user response:
In the case of AdminDirectory at Advanced Google services, it seems that AdminDirectory.Users.Photos.get("###").photoData
returns the byte array of int8array. In this case, how about the following modification?
From:
function hentSkolefoto() {
var photo = AdminDirectory.Users.Photos.get("[email protected]");
Logger.log(typeof(photo.photoData));
Logger.log(photo.photoData.toString());
}
To:
From your reply of What I would like to end up with is a string, I can put in here:' document .getElementById("img") .src = "data:image/jpg;base64," photodata;'
, when the value of photo.photoData
is converted to the data URL, how about the following modification?
function hentSkolefoto() {
var photo = AdminDirectory.Users.Photos.get("[email protected]");
var byteArray = photo.photoData;
var dataUrl = `data:image/png;base64,${Utilities.base64Encode(byteArray)}`; // When the mimeType of photo is PNG.
console.log(dataUrl); // You can see the value at the console.
// do something.
}
If you want to create the data as a file, you can also use the following sample script.
function hentSkolefoto() {
var photo = AdminDirectory.Users.Photos.get("[email protected]");
var byteArray = photo.photoData;
var blob = Utilities.newBlob(byteArray); // or Utilities.newBlob(byteArray, "mimeType", "filename")
DriveApp.createFile(blob);
}
- By this modification, the byte array is converted to the data URL.