Image to base64 and base64 to Image

Convert any, reasonably sized, file into "data:;base64..." URL for resource embedding purposes.

by Pankaj Sapkal

HTML

<fieldset>
    <legend>File upload controls:</legend>
    <input id="upload" type="file" />
    <div id="drop">
        <div class="title">DRAG AND DROP ANY FILE HERE</div>
    </div>
</fieldset>
<fieldset>
    <legend id="filename">Result:</legend>
    <textarea id="result" readonly="readonly" cols="20" rows="2"></textarea>
</fieldset>
<img id="img" />

CSS

#drop {
    border: 1px dashed #888;
    width: 86%;
    height: 25px;
    position: relative;
}
#drop:hover {
    background-color: rgba(0, 0, 0, 0.1);
}
#drop .title {
    position: absolute;
    top: 4px;
    left: 0px;
    text-align: center;
    width: 100%;
    z-index: 100;
}
#result {
    width: 86%;
    height: 25em;
}

JavaScript

/**
 * Copyright (c) 2013 Block Alexander
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 */
jQuery(document).ready(function ($) {
    $("#upload").on("change", OnGetFile);
    $("#drop").on("drop", OnGetFile);

    function OnGetFile(e) {
        $("#filename").html("get ready...");
        e.stopPropagation();
        e.preventDefault();
        var file = null;
        if (e.dataTransfer) { // file drag and drop
            file = e.dataTransfer.files[0] || null;
        } else if ($("#upload")[0].files) { // file upload
            file = $("#upload")[0].files[0] || null;
        }
        if (!file) {
            return;
        }

        var reader = new FileReader();
        reader.readAsDataURL(file, "UTF-8");
        reader.onload = function (e) {
            $("#filename").html("Result: '" + file.name + "' (" + e.target.result.length + " B)");
            $("#result").val(e.target.result);
            $('#img').attr('src', $("#result").val());
        };
        reader.onerror = function (e) {
            $("#result").val(e.target.error);
            $('#img').attr('src', $("#result").val());
        };
    }
});