Monday, 3 December 2018

How to get img data (like pixel) from an ajax call?

I have a image here : https://tx3.travian.fr/hero_body.php?uid=446, by using a userscript (with Tampermonkey) I know how to read pixel data but this script runs on the page itself, so it has to be open :

var img = $('img')[0];
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(195, 56, 1, 1).data;


If possible, I want to achieve that from another page of the website, make a get call and manipulate the img, but I only get weird data (unknown encoding or something else) and I don't know how to deal with the result :

$.get(link , function( data ) {
    // test 1
    //let obj = $(data).find('img');

    // test 2
    $$("#content").html('<img src="data:image/png;base64,' + data + '" />');

    // test 3
    let img = data;

    let canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

    var pixelData = canvas.getContext('2d').getImageData(195, 56, 1, 1).data;
});

  • The image is well-load, i can see in "preview" tab, and everything is ok here :

enter image description here

  • But then how to deal with it :

enter image description here

Edit

$.get( link, function( data ) {

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext("2d");

    var image = new Image();
    image.onload = function() {
        ctx.drawImage(this, 0, 0);
    };
    image.src = "data:image/png;base64," + data;   // ERROR GET data:image/png;base64,%EF%B ... F%BD net::ERR_INVALID_URL

});


To try : just open the dev console on the login page https://tx3.travian.fr/ and execute (the img page does not require login) :

$.get("/hero_body.php?uid=446" , function( data ) { console.log(data) });



from How to get img data (like pixel) from an ajax call?

No comments:

Post a Comment