Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to convert image into base64 string using javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.37k
    Comment on it

    Here is the example that shows converting an image file to base 64 string code. It can be done by the canvas method.
    HTML5 provides the canvas tag that is used to draw a canvas.

    For converting an image file to base 64 string you need to create a canvas and load your image into that. After this, you can use the  toDataURL() method to get the string in base64 format.

    Code:

    function encodeImage(src, callback) {
        var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d'),
            img = new Image();
    
        img.onload = function() {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);
            callback(canvas.toDataURL());
        }
        img.src = src;
    }

    You have to call the above function from your code after uploading the image file. Canvas can be used in almost all the browsers.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: