1

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

Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179
  • Have you looked at this post--especially relating to manually parsing your raw jpeg camera streams: http://stackoverflow.com/questions/28827670/create-html-canvas-from-ajax-arraybuffer-response-type/28827942#28827942 – markE May 09 '15 at 17:33
  • Not unless you are willing to implement a JPEG decoder in Javascript. – Philipp May 09 '15 at 19:05
  • @philipp thank you. I have now established that fact. Image element is the best thing to use :) – Andrew Simpson May 09 '15 at 19:26

1 Answers1

1

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.