1

I am working on a project where I need to convert a base64 dataUri to Uint8ClampedArray without using HTML5 Canvas. This is what I have came up with but I think the Uint8ClampedArray doesn't represent the pixel table.

function dataUri2Array(uri){
    b64 = uri.slice(uri.indexOf(',')+1);
    str = atob(b64);
    arr = str.split('').map(function (e) {return e.charCodeAt(0);});
    u = new Uint8ClampedArray(arr);
    return u;
},
Pooja Patel
  • 11
  • 1
  • 3
  • you have to populate the array in the map(), not all at once after... – dandavis Sep 03 '14 at 18:30
  • Just use html5 canvas--it won't bite you. – markE Sep 03 '14 at 18:42
  • @dandavis Can you please elaborate? May be with a few lines of codes? – Pooja Patel Sep 03 '14 at 18:43
  • @markE That's not an answer! – Pooja Patel Sep 03 '14 at 18:44
  • You're correct...that's why I posted it as a comment. Why not use html5 canvas since it is a good tool for the job? – markE Sep 03 '14 at 18:48
  • @markE I meant, I was looking for an answer, not an alternative. – Pooja Patel Sep 03 '14 at 19:39
  • Why not use html5 canvas? I ask because, as David Titarenco says, you will need to find/code multiple image decoders. Each image decoder is hundreds of lines of code--at least! I'm just trying to push you in a path of least effort instead of "reinventing the wheel". Good luck with your project. :-) – markE Sep 03 '14 at 19:50
  • I understand that this problem can be solved by simply using Canvas. But I am working on a platform that doesn't support Canvas rendering. Which is why I need to encode/decode entirely on my own. Thanks. – Pooja Patel Sep 03 '14 at 19:56

1 Answers1

3

Since you don't want to use Canvas, you'll need to implement encoding/decoding for various image types yourself. Your code will look something like:

function dataUri2Array(uri){
    b64 = uri.slice(uri.indexOf(',')+1);
    type = getImageType(uri); // *
    data = atob(b64);
    switch (type) {
    case "jpeg":
         arr = decodeJpeg(data);
         break;
    case "gif":
         arr = decodeGif(data);
         break;
    case "png":
         arr = decodePng(data);
         break;
    default:
         break;
    }
    u = new Uint8ClampedArray(arr);
    return u;
}

The getImageType(uri) function and all the decodeX(data) functions need to be implemented. Here are some libraries that might help: jpeg-js, node-pngjs, bmp-js, etc. Getting the pixel arrays from arbitary data is nontrivial, especially when dealing with non-raw types (i.e. BMP).

If you want to write the decompressors yourself, the Wiki page may be a good introduction, but I also suggest reading up on Shannon-Fano and other kinds of encoding methods to familiarize yourself with the concept.

I hope you have a good reason for not using Canvas.

David Titarenco
  • 32,662
  • 13
  • 66
  • 111