Thursday, October 30, 2014

Image convert to String using Javascript

I am working as phonegap developer past 1 year. I want to save the image in my database. so i want to convert image to string .

 Create a canvas, load your image into it and then use toDataURL() to get the base64 representation (actually, it's a data: URL but it contains the base64-encoded image)



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>File Transfer Example</title>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
   </head>
<body>
  <input type="file" id="file" />
<div id="imgTest"></div>
<div id="testing"></div>
<script type='text/javascript'>
var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {
    var file, img;


    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function() {
if(this.width > 150 && this.height > 150 )
            {
            alert("please upload image size 150 X 100");
            }
            else{
            var filesSelected = document.getElementById("file").files;
    if (filesSelected.length > 0)
    {
        var fileToLoad = filesSelected[0];

        var fileReader = new FileReader();

        fileReader.onload = function(fileLoadedEvent) {
            var srcData = fileLoadedEvent.target.result; // <--- data: base64

            var newImage = document.createElement('img');
            newImage.src = srcData;

            document.getElementById("imgTest").innerHTML = newImage.outerHTML;
            alert("Converted Base64 version is "+document.getElementById("imgTest").innerHTML);
            console.log("Converted Base64 version is "+document.getElementById("imgTest").innerHTML);
   document.getElementById("testing").innerHTML = srcData;
        }
        fileReader.readAsDataURL(fileToLoad);
    }
            }
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);


    }

});
</script>
</body>
</html>

No comments:

Post a Comment