Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    rjw
    rjw is offline
    New to the CF scene
    Join Date
    Jul 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy HTML5/javascript canvas interpreting base64 string as image

    Hi...I'm an HTML5 newb.

    I was able to figure out how to convert an image to a base64 string and save the string for future viewing:
    var oCanvas = document.getElementById("canvas");
    oCanvas.toDataURL() //- this is a base64 encoded PNG file returned in URI format.
    Canvas2Image.saveAsPNG(oCanvas, true) //- this returns an html <img> element which can be saved


    So now I have a huge string: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABU[...I won't bore you with the stuff in the middle - but it's a really long string...]rkJggg==

    How do I load that string up in a browser (I'm using Firefox 5.0) to display? I found several posts on Google referring to drawImage, and so this is what I have:
    function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    var image = new Image();
    img.onload = function () {
    ctx.drawImage(img, 0, 0);
    }

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

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    }


    But all this does is return the string back to me when I call getBase64Image.

    Any help would be so appreciated.

    Thank you!

  • #2
    The Apostate Apostropartheid's Avatar
    Join Date
    Oct 2007
    Posts
    3,215
    Thanks
    16
    Thanked 265 Times in 263 Posts
    You shouldn't need a canvas to do this: Firefox should interpret the string as the src of an img element just fine.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •