Search code examples
asp.net.nettypescriptaureliaemgucv

Send umat or image in memory to web client and display in html


I have a aurelia client that gets a image from my asp.net server via my API. The image is stored as a png file and is loaded when the api call is done.

This works fine but the image is from a webcam that gets images via Emgu cv.

My question is if it is possible to directly serve the current Umat/Mat image and display it on the webpage.

 HttpResponseMessage response = new HttpResponseMessage();
        try
        {

         Console.WriteLine("Get image 3");
        manager.sem.WaitOne();

        // Maybe firsto to Emgu cv Umat to .net Image (bitmap?)
        // Then image to byte.memory stream
        // Send

        Image<Bgr, Byte> myImage = new Image<Bgr, Byte>(ddEngine.ResultImage.Bitmap);

        response.Content =
            new StreamContent(new MemoryStream(opencvCam.ResultImage.Bytes));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");


        manager.sem.Release();
    }
    catch
    {
        Console.WriteLine("ex");
    }

My client code looks like this:

  updateImageSrc() {
    let dt = new Date();
    let baseUrl = "http://localhost:8080/api/status/dummymethod3";
    this.imagePath = baseUrl + "?t=" + dt.getTime();
}

And the html

    <img id="img" src.bind="imagePath"/> 

The page does not display any image.


Solution

  • I see you already have a work around using

    result.Content = new ByteArrayContent(memoryStream.ToArray());
    

    I don't think that converting to an array is the most efficient way (you should see some performance degradation with larger images)

    My recomendation use the StreamContent. Your code needs to change a bit:

    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("dummymethod3")]
    public HttpResponseMessage Get2()
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            Console.WriteLine("Get image 3");
            ddEngine.sem.WaitOne();
    
            var memoryStream = new MemoryStream();
            ResultImage.Bitmap.Save(memoryStream, ImageFormat.Png);
            memoryStream.Position = 0;
    
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(memoryStream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
    
            ddEngine.sem.Release();
    
            return result;
        }
        catch
        {
            Console.WriteLine("Ex");
        }
    
        return response;
    }