Search code examples
javascriptimage-processinghtml5-canvasgeneric-handler

Load image into canvas using a generic handler


is it possible to load an image directly into a canvas control using a generic handler without using the image element?

This is my handler:

    public void ProcessRequest(HttpContext context)
    {
        context.Response.AddHeader("Access-Control-Allow-Origin", "*");
        context.Response.ContentType = "image/jpeg";
        var camIndex = Convert.ToInt16(context.Request.QueryString["camIndex"]);
        context.Response.BinaryWrite( Shared.Feeder[camIndex].JpegData);           
    }

My JavaScript:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/Media/FrameHandler.ashx?camIndex=' + camIndex, true);                     
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    var uInt8Array = new Uint8ClampedArray(this.response);
    imageData[camIndex].data.set(uInt8Array);
    ctxLiveViews[camIndex].putImageData(imageData[camIndex], 0, 0);
};
xhr.send();

which gives me this image (which is obviously wrong)

enter image description here


Solution

  • Is it possible to load an image directly into a canvas control using a generic handler without using the image element?

    It is, but you are in for a hand-full as you will need to manually parse the image file format yourselves (with all the various combinations of image format, color model etc. and error checks and so forth). It's doable (been there done that), but chances are, unless you need to access some special data or bitmap formats, that the browser will do the job at least faster than a manual approach in JavaScript.

    Using an Image element is easy and does all these steps for you in compiled code.

    This line:

    var uInt8Array = new Uint8ClampedArray(this.response);
    

    will only hold the original file bytes, uncompressed, undecoded including header, chunks and metadata. While putImageData() require a raw bitmap in the format RGBA per pixel. This is why you see the noise as the data being fed to putImageData is the file itself, not a bitmap.