Thursday, 19 March 2015

Example of Writing Image to File in Apache Cordova

Below is an example of how to writing image to a file in Apache Cordova. To have more understanding of basic file operations, please see my previous post.
window.resolveLocalFileSystemURL(my_Directory_Path,
function (dirEntry) {
 dirEntry.getFile(path_Of_File_To_Be_Written, { create: true }, 
  // getFile() success
  function (fileEntry) {
   fileEntry.createWriter(
    // createWriter() success
    function (fileWriter) {
     fileWriter.onwriteend = function (e) {
      . . .
     };

     fileWriter.onerror = function (e) {
      . . .
     };

     fileWriter.write(dataURIToBlob(getBase64Image(image_To_Be_Written, "image/jpeg")));
     // or if we already have a canvas
     //fileWriter.write(dataURIToBlob(canvas.toDataURL("image/jpeg")));
    }, 
    // createWriter() error
    function (error) {
     . . .
    }
   );
  },
  // getFile() error
  function (error) {
   . . .
  }
 );
});

A function to convert an image's base-64 encoded data to Blob type (this is taken from http://stackoverflow.com/questions/12391628/how-can-i-upload-an-embedded-image-with-javascript):
function dataURIToBlob(dataURI) {
 // serialize the base64/URLEncoded data
 var byteString;
 if (dataURI.split(',')[0].indexOf('base64') >= 0) {
  byteString = atob(dataURI.split(',')[1]);
 }
 else {
  byteString = unescape(dataURI.split(',')[1]);
 }

 // parse the mime type
 var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

 // construct a Blob of the image data
 var array = [];
 for (var i = 0; i < byteString.length; i++) {
  array.push(byteString.charCodeAt(i));
 }
 return new Blob(
  [new Uint8Array(array)],
  { type: mimeString }
 );
}
Also a function to get base-64 encoded data from an image:
// type is either "image/png" or "image/jpeg"
function getBase64Image(img, type) {
    // create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // get the base-64 encoded data
    var dataURL = canvas.toDataURL(type);
 // toDataURL() actually has two optional parameters:
 // - type. The default value is 'image/png'.
 // - jpegQuality. A decimal value ranging from 0 to 1 to determine the quality of the data to be generated from a jpeg type image.
 //   The default value is browser dependant.

    return dataURL;
}

No comments: