Search code examples
javascriptbinarytitaniumjpegappcelerator

Can you recommend a JavaScript JPEG library without an HTML or atob dependency?


I'm having some issues reading JPEG binary data with JavaScript and looking for some recommendations on libraries or alternative approaches.

I am working to modify an open source PDF generation library called jsPDF so that it will work with an Appcelerator Titanium Alloy 3.41 project. The issue I am running into is that while Titanium uses JavaScript the implementation does not support all data types or methods.

For example, most of the JPEG libraries I have found use the atob and btoa methods which are implemented in web browsers to encode/decode base64 data into binary strings. Unfortunately the project I am creating does not use a web browser and even if I changed my approach Titanium's WebView does not support the atob or btoa methods.

I've also tried using Titanium's base64encode and base64decode utilities however they return a Blob instead of a binary string and most methods I have seen for converting base64 to a binary string requires an ArrayBuffer which Titanium also does not implement.

I'm following the following steps to generate a PDF:

  1. Create a dataURI by reading in the JPEG into a Blob and converting it to base64.

    var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA.....ooA//2Q==';

  2. The library then extracts the image data from the dataURI. The library then uses the atob method to convert the base64 into a binary string and then if the environment supports ArrayBuffers a function is used to convert the ArrayBuffer to a Uint8Array which Titanium does support. From there the binary data is used to extract the JPEG height, width, etc.

Code extract from jsPDF

var base64Info = this.extractInfoFromBase64DataURI(imageData);
if(base64Info) {
  format = base64Info[2];
  imageData = atob(base64Info[3]);//convert to binary string, the base64 encoded JPEG 
 } 

.....

if(this.supportsArrayBuffer()) {
  dataAsBinaryString = imageData;
  imageData = this.binaryStringToUint8Array(imageData);
}

.....

function binaryStringToUint8Array(binary_string) {
  var len = binary_string.length;
  var bytes = new Uint8Array( len );
  for (var i = 0; i < len; i++) {
    bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes;
};

Solution

  • I ran into the same problem in IE 9 with jspdf.plugin.addimage.js, where atob is not implemented. Would you be able to try this polyfill? https://github.com/davidchambers/Base64.js