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.

Chad Dienhart
  • 5,024
  • 3
  • 23
  • 30

1 Answers1

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.

Giedrius
  • 8,430
  • 6
  • 50
  • 91
  • 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. – Chad Dienhart Oct 03 '14 at 19:49
  • 1
    The base64 representation of an image is larger than just the binary. http://stackoverflow.com/questions/11402329/base64-encoded-image-size – GM Lucid Oct 04 '14 at 01:33
  • 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 – Anders Oct 07 '14 at 07:05