2

This is my first ASP.NET application and I'm having trouble passing a server side Bitmap object to the JavaScript client. I'm using SignalR to connect the server and client.

I've tried several things and hope this is easy for someone with ASP.NET experience.

Here is my server side C#:

    public void ScreenShot()
    {
        Rectangle bounds = this.Bounds;
        using (Image bitmap = new Bitmap(bounds.Width, bounds.Height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
            }

            Clients.Caller.updateImage(bitmap);
        }
    }

On the client side I want to get the Bitmap and display it:

        hubproxy.client.updateImage = function (image) {
            var img = document.createElement("img");
            img.src = image;
            document.body.appendChild(img);
        };

Do I have to convert it to a JSON object? If I do this how do I get it back to an image on the client side?

Thanks in advance for helping.

1 Answer 1

7

You could convert image to byte array:

public static byte[] ImageToByte(Image img)
{
   ImageConverter converter = new ImageConverter();
   return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

And then enocde it to base64 - and you can use base64 as image source in html:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." />

Another way would be to save that image on server and return only link to the path on server, you could use something like GUID to produce unique name and periodically cleanup old images or cleanup after client disconnect, etc. Advantage of this would be smaller network traffic on large images - you would save ~37% of traffic by sending just file name.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that works great. How do you save on network traffic, given that the image file still needs to be transferred? I thought that by sending the raw data I'd save some time by not incurring the cost of writing the image to disk.
The base64 representation of an image is larger than just the binary. stackoverflow.com/questions/11402329/base64-encoded-image-size
You do not need to write it to disk, you can in memory cache it and let the controller return the image using a GUID as identfier. Use SignalR to publish that GUID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.