Home > Software design >  Getting image data back from jQuery ajax request and displaying it in img tag
Getting image data back from jQuery ajax request and displaying it in img tag

Time:09-07

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"

CodePudding user response:

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 try

var response = fake_api_result();
var prefix = 'data:image/png;base64,'
document.querySelector("#img").src = prefix   btoa(response)



function fake_api_result() {
  var base64 = `iVBORw0KGgoAAAANSUhEUgAAAHYAAABgCAYAAADIKIaXAAAAAXNSR0ICQMB9xQAAAAlwSFlzAAAXEgAAFxIBZ5/SUgAAABl0RVh0U29mdHdhcmUATWljcm9zb2Z0IE9mZmljZX/tNXEAAAgdSURBVHja7V0rkBtHED0YGBh4FeRyVSSnQgIFDx48KChoGJhDhoGuA1dniQgGGgYaHhRymdztqgISKJhotL e3tndmdnunpmVwFa5XLZ2d970573u6b26v7 /4rhmT9lqtt7/O1/n/10u43WYb/YfuNaf5Ud/fsoWF DsrqMB/JYEsL88fP1 vs7y4sGz/N06/536mm/yz/XifHp9ov/9/Ydm8V /sLzDOt9Vljt7zN5ED6xa6GY3vtyxuPn1/rnaOD8 fP2O4x7zT/s/Oe hwDy5Y7VOx/ehvgdxXH25g5bE5OZvq3sc//yeMUe44b6P t16vYjjLdkPvX3454cqWZqts2/KJbNYUu2G axV0jP8tMn AhtoER2wXA oxe/H7B3XDh/yDlxh5fhO1xwGEb1LMce9/KA8BDewp3uWSY6yXsYNtKQOYdEnASZrnW32f0iAijetsmDGTbsFFOgmKLAKRJi2q8Vne/FN/rF6cSlrbd6xom vX7jug2ni2HccZ61Hy Em2lViVnkF5Y6lQDVZLefm1YSdY5IYBFj4ECpxYs1OwQbiXFgrq2XeWNAzKVlWFFjoNlRGpzI7zkWtNecA1toseKNGcW4uHN58VanR6pLK6KbgBmMKB7PHv3 t7 UZ10eqS/utlAvkpBseIYGdbpV68mmd1Z9ZgYXqEkXmFgvVcBETJCmXslZfxuEa2D9Tcq2UrDWESFJupNIl5zsXjcDBBWcrkIp/ZHd7wOXHYK2hhBKoSr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CmONv6BcRo7O7A6Fx3ndnSrket7ht5iTNYq2Y0iAixlolBTH8GGbOB1vClOK6EUaA4UWRxc7vPNblFmyr446EDz1vOZl/CwlMRziwFr4m0 bk2a kBL86E4uPwmycNFk5AC3HHlvirb5h5QOXbUD5RZpWZQBgO2TEZGaaNS1Afp1EvH/7sIcQ4qKLCn3fyYvUHVjFsf6sPZOuNLcdqlzDB9W0GANSyA067mrvr4fkPPsGGXodY3GLCmOOSSXHBSHx KYzj9FrQ5ICiwAFznzBFSH8oTgT4zm3BSGEOze3BgMdezJfBc1EffMMOZbLv8xv 9hGSAbS2oJbiw8E1FfVwojronHHwmPd8pCWDV5aqnUlMfpEevBnkulEoj6PCIFlhkhVYVEGAxO4J7W38mXKr8NhlgXReNivq4TDeXLL9NClgXN0c1hgc2BvRRHOny26SAdU1MtMX2oD62w6Sp 7nOElgTlehykZB7 lAfLSPvUMBCDFyZLLCArw723lZx2afqM3RsE/dMpzAsO3pgy8Tmeqjch7r0Vw7W2jujaYzseQHWEtyu8XKNuFBUZFyqPn0fIAw1hvCsgK0Wuu90Hxr2sRj6vb4ZTfheMX3qdHLAnlxjzxlSdGB6kPqgOf7XLt7hAiwHuD1xz/bAdBf/ja38dlbAFuCaG8Vsx SaxtBynn67AOtmuStTa6fNrCjAj3cmzhxTpebsgG2pTqVwMDQmF1OcmMtvZwtsG9xCv 0THfAYWqxLpzoMe3LAQuUJfDjC2AmB5UepUYIXYInALV1r63gGnuaaQqXm7IEtgANuFXyyRFmqRnH079RMCtRJAtuq5QLqoh QSqdScwFWV6Ce8WfBTH83RVAnC2zDSxsFyfSZsBS/VXv2wJ7ARfIgjLlTBnXywFbgooQpqfLbBdh cKsS3FmAqq7/AXyqhsdibchKAAAAAElFTkSuQmCC`
  return atob(base64)
}
<img id="img">

In your case, your code should look like and hopefully work:

$.ajax(settings).done(function (response) {
    
    var base64 = btoa(response)

    var img = $('<img id="dynamic">');
    img.attr('src', "data:image/png;base64,"   base64);
    img.appendTo('#imgcontainer');

});

CodePudding user response:

In your case, you don't need fake_api_result function. You may try this

var prefix = 'data:image/png;base64,'

function encodeAndDisplayResult(data){
    var encoded = btoa(data);
    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);


});
  • Related