C# Grab image from web and put it in a SQL Server Table.

This code example demonstrates Csharp programming techniques and best practices.

public byte[] get_image_bytes(String url)
        {

            Image image = null;
            Image thumb = null;

            WebClient webClient = new WebClient();
            byte[] current_data = null;

            MemoryStream ms = new MemoryStream();

            try
            {
                current_data = webClient.DownloadData(url);
                image = Image.FromStream(new MemoryStream(current_data));
                thumb = image.GetThumbnailImage(150, 150, null, IntPtr.Zero);
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                return ms.ToArray();
            }
            catch (Exception ex)  // could not find the image or write it. 
            {
                while (ex != null)
                {
                    ex = ex.InnerException;
                }
                return null;
            }
          }

Language: Csharp
Original Source: BlogEngine.NET Migration
Code Lines: 73

Create a table in SQL to hold your images byte data. 

Your image column / field should look like this:

 

varbinary works well for saving image to SQL.

Code for grabbing the image from the web and store it in a byte array. 

Store the byte array in SQL. 

 

 

 

C# Grab image from web and put it in a SQL Server Table.

  Create a table in SQL to hold your images byte data.  Your image column / field should l