Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert base64 to image in javascript/jquery

I have written some code for image capturing using javascript/jquery Below is the code:

function capture_image(){      alert("capture_image");     var p = webcam.capture();     webcam.save();                alert("capture complete "+p); //getting true here        var img = canvas.toDataURL("image");     var item_image = img.replace(/^data:image\/(png|jpg);base64,/, "") ;      alert("item_image"+item_image); } 

The item_image print the base64 format, How to convert that base64 to image and how to use that path in javascript clientside.

Am searching google so many websites but its not working and that code is not suitable for my requirement.

like image 810
user2996174 Avatar asked Jan 20 '14 05:01

user2996174


People also ask

How can I convert Base64 image to typescript?

If you have a data url and you want it to be shown in an img element, just set the src to the data url. You don't need to convert it to an image. Even so, just use the image as your feed to the <image-cropper>. Just create an image, set the src to the data URL, and use that image for your <image-cropper>.

How do I make an image Base64?

You can just create an Image object and put the base64 as its src , including the data:image... part like this: var image = new Image(); image. src = 'data:image/png;base64,iVBORw0K...'; document.

How does Base64 look like?

Base-64 maps 3 bytes (8 x 3 = 24 bits) in 4 characters that span 6-bits (6 x 4 = 24 bits). The result looks something like "TWFuIGlzIGRpc3Rpb...".


2 Answers

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image(); image.src = 'data:image/png;base64,iVBORw0K...'; document.body.appendChild(image); 

It's what they call "Data URIs" and here's the compatibility table for inner peace.

like image 58
Joseph Avatar answered Sep 21 '22 06:09

Joseph


This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {     contentType = contentType || '';     var sliceSize = 1024;     var byteCharacters = atob(base64Data);     var bytesLength = byteCharacters.length;     var slicesCount = Math.ceil(bytesLength / sliceSize);     var byteArrays = new Array(slicesCount);      for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {         var begin = sliceIndex * sliceSize;         var end = Math.min(begin + sliceSize, bytesLength);          var bytes = new Array(end - begin);         for (var offset = begin, i = 0; offset < end; ++i, ++offset) {             bytes[i] = byteCharacters[offset].charCodeAt(0);         }         byteArrays[sliceIndex] = new Uint8Array(bytes);     }     return new Blob(byteArrays, { type: contentType }); } 

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

... window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {                      // Setup filename and assume a jpg file                     var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");                     dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {                         // attachment.document holds the base 64 data at this moment                         var binary = base64toBlob(attachment.document, attachment.mimetype);                         writeFile(fileEntry, binary).then(function() {                             // Store file url for later reference, base 64 data is no longer required                             attachment.document = fileEntry.nativeURL;                          }, function(error) {                             WL.Logger.error("Error writing local file: " + error);                             reject(error.code);                         });                      }, function(errorCreateFile) {                         WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));                         reject(errorCreateFile.code);                     });                  }, function(errorCreateFS) {                     WL.Logger.error("Error getting filesystem: " + errorCreateFS);                     reject(errorCreateFS.code);                 }); ... 

Writing the file itself:

function writeFile(fileEntry, dataObj) {     return $q(function(resolve, reject) {         // Create a FileWriter object for our FileEntry (log.txt).         fileEntry.createWriter(function(fileWriter) {              fileWriter.onwriteend = function() {                 WL.Logger.debug(LOG_PREFIX + "Successful file write...");                 resolve();             };              fileWriter.onerror = function(e) {                 WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());                 reject(e);             };              // If data object is not passed in,             // create a new Blob instead.             if (!dataObj) {                 dataObj = new Blob(['missing data'], { type: 'text/plain' });             }              fileWriter.write(dataObj);         });     }) } 

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

like image 44
Jürgen 'Kashban' Wahlmann Avatar answered Sep 20 '22 06:09

Jürgen 'Kashban' Wahlmann