I’m using the dezgo api and whenever I get a response, I want to display it in an image tag. This is my code:
const settings = {
"async": true,
"crossDomain": true,
"url": "https://dezgo.p.rapidapi.com/text2image",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"X-RapidAPI-Key": "#####################",
"X-RapidAPI-Host": "dezgo.p.rapidapi.com"
},
"data": {
"steps": "10",
"guidance": "-20",
"width": "512",
"prompt": "an insect",
"height": "512"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
var img = $('<img id="dynamic">');
img.attr('src', "data:image/png;base64," + response);
img.appendTo('#imgcontainer');
});
but I just wind up with an img like this:
<img id="dynamic" src="data:image/p�PNG
�
���
IHDR�������������{�C�����IDATx�<��dK�߉������g���7�2Y$�"�d��Z���ѣ�I��B� B�[
���"�*o��F����`fk������p"����{o���~���������Q-�si�^$Q�5����_���@"�__������v������Vۛ��% ��<�HÐ�8���o���y�[�<=����7�˺�U���
�xwwLi����w_}�
It seems like it isn’t encoding the data.
EDIT: I modified this using IT goldman’s suggestion
// var response = fake_api_result();
var prefix = 'data:image/png;base64,'
// document.querySelector("#img").src = prefix + btoa(response)
function fake_api_result(data) {
var base64 = data;
return atob(base64)
}
function encodeAndDisplayResult(data){
var unencoded = fake_api_result(data);
var encoded = btoa(unencoded);
var img = $('<img id="dynamic">');
img.attr('src', prefix + encoded);
img.appendTo('#imgcontainer');
}
const settings = {
"async": true,
"crossDomain": true,
"url": "https://dezgo.p.rapidapi.com/text2image",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"X-RapidAPI-Key": "####################",
"X-RapidAPI-Host": "dezgo.p.rapidapi.com"
},
"data": {
"steps": "10",
"guidance": "-20",
"width": "512",
"prompt": "an insect",
"height": "512"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
encodeAndDisplayResult(response);
});
Now it says: "Uncaught DOMException: String contains an invalid character"
2
Answers
It looks like a raw PNG data. That’s a binary I think so you need to convert it to base64 and use it directly as
src
of image. Alternatively, maybe some kind of reader idk. Lets tryIn your case, your code should look like and hopefully work:
In your case, you don’t need fake_api_result function. You may try this