1

I have a form. When user click save, i want to get the image that he/she selected and convert it to base64 and return that. Is it possible?

This is my CODE so far

<script src="jquery-2.1.4.min.js"></script>
<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>

<script type="text/javascript">
    $('#i_file').change( function(event) {
        var tmppath = URL.createObjectURL(event.target.files[0]);
        $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

        $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");

        $type = pathinfo(tmppath, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
        console.log($base64);

    });
</script>
Ali Zia
  • 3,825
  • 5
  • 29
  • 77

1 Answers1

0

You can't directly convert an image into base64 encoding using javascript, but you can paint the image onto a 2-dimensional HTML5 canvas and then convert the canvas-painted image into base64 encoding using javascript.

You can approach this in 3 steps:

  1. Load the full-version of the selected image to the page (if it isn't already an existing element on the page);
  2. Copy the newly-loaded image across to an HTML5 canvas element
  3. Convert the canvas to a base-64 data URL

Working Example:

var body = document.getElementsByTagName('body')[0];

function convertImage() {
    this.crossOrigin = 'Anonymous';
    var canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;
    var canvasContext = canvas.getContext('2d');
    canvasContext.drawImage(this, 0, 0);

    var base64URL = canvas.toDataURL();
    var paragraph = document.createElement('p');
    paragraph.textContent = base64URL;
    body.appendChild(paragraph);
}


function loadImage() {
    var image = document.createElement('img');
    image.setAttribute('src','http://placehold.it/140x200');
    image.setAttribute('alt','Placeholder Image');
    body.appendChild(image);
    image.addEventListener('load',convertImage,false);
}

window.addEventListener('load',loadImage,false);
img, canvas, p {
display: inline-block;
margin-right: 12px;
width: 140px;
height: 200px;
}

p {
font-size: 9px;
overflow: scroll;
}

N.B. The example above throws a security error, but only because CORS (Cross Origin Resource Sharing) recognises that the image in the example is an external source - and it is a security issue to start encoding a canvas which has content written to it from an external source.

If the image being painted to the canvas is from the same origin, then there will be no security error.

Rounin
  • 27,134
  • 9
  • 83
  • 108