Can't get avatar data from inside api

I am building an Android App which is able to modify the Nextcloud user’s avatar without accessing Nextcloud web.

After not finding an external api to set avatar I turned to custom api but found some issue.

I uploaded a custon avatar on Nextcloud web then write my code in my controller function below:

$credentials = $this->credentialStore->getLoginCredentials();
$avatar = $this->avatarManager->getAvatar($credentials->getLoginName());
$avatarImage = $avatar->get(-1); // -1 means original size not cropped or resized.
$avatarWidth=avatarImage->width(); // This seems outputting the correct value. 
$avatarData = $avatarImage->data(); // This should return an base64 string or what.
return json_encode($avatarImage);

Any size I tried results in an empty string.

Wondering what I’m doing wrong or it’s not a ready function in Nextcloud. Can anyone help on this one? Thanks in advance.