Return Binary Image Using Web Api and Knockout.js

If you have a SQL database that has an image field  in a particular table and want to return the image to the web site using web API’s then you almost have to extract the image as binary, read it to a memory stream and then save it temporarily on the server.  Pass the location back to the web page where the web page then displays the image.

What if you don’t want to create a temporary file or what if you have a lot of images for a particular product you know the user is not going to look at all of them, but since they could you’re left to run through this process anyway.  Here is another way you could do this.  Instead of creating a temporary file just stream the image back in the way of a string.  Then let your browser convert it to the binary image equivalent.

On your asp.net web API side convert the image to a string like so…. (Assuming that the LINQ result set is ‘x’ and fieldname is ‘images’).

        Dim imagestream As Byte() = x.images.ToArray
        Dim imagestring as string = Convert.ToBase64String(imagestream)

Once you have this and you send it back to the browser you can place this in your page using a wide variety of methods. For the purposes of what I needed it for I used the syntax below using knockout.js.

  <img class="equipphoto" alt="" data-bind="attr: {src: "data:image/jpeg;base64," + imagefile, id: imageid } " />

Image gets displayed automatically.

Check Arvixe for great affordable web hosting and services.

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , | Posted under ASP .NET 4.0 | RSS 2.0

Author Spotlight

David Bauernschmidt

David Bauernschmidt

I live in the historical triangle of Virginia where I am married with two daughters. I have spent over 13 years working for a Fortune 500 company in the computer area. I started in VB 6.0 and by the time I ended my employment I was supervising a development team where we built many web applications. When my first daughter was born I wanted to spend more time with her so I left and became a programmer analyst for local government as well as launch my own company. Since then I have grown James River Webs into a profitable web design and application company helping small businesses create a big presence on the internet. As an employee I have created web application used by citizens and other companies. I enjoy fly fishing, and spending time with my family. I also enjoy learning new approaches and development tools when it comes to developing applications.

Leave a Reply

Your email address will not be published. Required fields are marked *


7 − 5 =

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>