Is it somehow possible to convert an byte array to image data without using canvas?
I use currently something like this, however I think that can be done without canvas, or am I wrong?
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
var byteArray = [
255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, // red
0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, // green
0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255 // blue
];
var imageData = ctx.getImageData(0, 0, 10, 3);
for(var i = 0; i < byteArray.length; i+=4){
imageData.data[i] = byteArray[i];
imageData.data[i+1] = byteArray[i + 1];
imageData.data[i+2] = byteArray[i + 2];
imageData.data[i+3] = byteArray[i + 3];
}
ctx.putImageData(imageData, 0, 0);
http://jsfiddle.net/ARTsinn/swnqS/
Update
I've already tried to convert it into an base64-uri but no success:
'data:image/png;base64,' + btoa(String.fromCharCode.apply(this, byteArray));
Update 2
To split the question from the problem
The canvas itself is it not, rather the fact that oldIE (and else) don't support it. ...And libraries like excanvas or flashcanvas seems a bit too bloated for this use case...
canvas.getImageData
returns an ImageData object that looks like this:
interface ImageData {
readonly attribute unsigned long width;
readonly attribute unsigned long height;
readonly attribute Uint8ClampedArray data;
};
(See the specs: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#imagedata)
I guess you could box your data fitting that interface and try it out.
If you try, let me know how it turns out :)
Alternatively, you could create an in-memory canvas of your desired width/height--document.createElement("canvas"), Then grab its imagedata and plug in your own array. I know this works. Yes...that goes contrary to your question, but you're not adding the canvas to your page.
Is there a reason you don't want to use canvas? This really is what canvas is for. Once you have the image data what would you do with it? Render it in the browser? Send to a server? Download to the user? If the problem is just that you don't want to have a canvas on screen you could create a hidden canvas to do the work.
来源:https://stackoverflow.com/questions/16137406/convert-a-byte-array-to-image-data-without-canvas