I'm newbie on this but I have this problem, I'm using an API which gives me as result a PNG image binary string:
I want to convert this to base64 and put it as an attribute in an img tag
<img id="ml">
So tried, doing this:
$("#ml").attr("src",'data:image/png;base64,'+ btoa(unescape(encodeURIComponent(response))) );
But this shows me a broken image:
I tried with this getting the same error:
var blob = new Blob([response], {type: 'image/png'});
var reader = new FileReader();
reader.onload = function (e) {
$('#ml').attr('src', e.target.result);
};
reader.readAsDataURL(blob);
Finally I used a library: https://github.com/dankogai/js-base64
var emk = Base64.encode(response);
$("#ml").attr("src",'data:image/png;base64,'+ emk );
But the result is the same.
I don't know if I'm missing something, I'd like to receive your help.
=====
UPDATE:
As you mentioned in the comments I mention the previous step:
I obtain this binary result from VanceAI API. I upload an image, then process applying an edition provided by API service and finally the result is for download, this is the code:
var form = new FormData();
form.append("api_token", "XXXXXXX1234AAAAAA");
form.append("trans_id", "XXXXBBBBVVVVVVVV"); //processed image ID
var settings = {
"url": "https://api-service.vanceai.com/web_api/v1/download?api_token=XXXXXXX1234AAAAAA",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response); // binary result
});
I also tried this:
$("#ml").attr("src",'data:image/png;base64,'+ btoa(response) );
But I get this error:
I also have to mention this result is not a Blob.
I hope you can help me.
Thanks.