0

I need images to be copied and sent to server for image rotations etc.

To copy an image I'm using this code( from Get image data in JavaScript?):

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    var replaced = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

    console.log("dataurl=",dataURL);
    console.log("replaced=",replaced);

    return replaced;
}

It is called like this:

$("#xyz").load(send_image).each(function () {
            if (this.complete)
                $(this).load();
        });

function send_image(){
      getBase64Image(document.getElementById('xyz'));
}

However in getBase64Image function once in 40-50 times dataURL is being returned as empty.

What could be the reason?

Community
  • 1
  • 1
user5858
  • 1,082
  • 4
  • 39
  • 79
  • CORS. Your image has to come from the same domain or with the crossorigin attribute set to Anonymous and the proper header sent from the server. – Kaiido Dec 05 '15 at 15:15
  • @Kaiido the images are all from the same domain. – user5858 Dec 05 '15 at 16:14
  • 1
    Is it the same image that returns empty each time? – markE Dec 05 '15 at 19:33
  • @markE yes it is the same one – user5858 Dec 06 '15 at 03:04
  • 1
    @user5858 then your image file might be corrupted. Can you load it in an img tag? – Kaiido Dec 06 '15 at 03:10
  • As @Kaiido says, the image is probably corrupt. Pull it into Photoshop and Save-As it to another file ... that almost always fixes it. :-) – markE Dec 06 '15 at 05:13
  • @markE but user is always able to see it in browser. I also see it. If it is corrupted slightly -- if browser is able to show the PNG image then I too should be able to correct it and copy it using the function above. – user5858 Dec 06 '15 at 14:21
  • @user5858. I know it sounds illogical, but I've seen it happen just that way. Can you post the offending image so we can take a look? – markE Dec 07 '15 at 01:24

0 Answers0