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;
},
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 (ie 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.