C# Image to byte array and byte array to image

C# Image to byte array and byte array to image

Here’s a simple example about how image can be converted to byte array and stored into MS Sql Database and retrieved back as image.

Table:

CREATE TABLE [dbo].[ProductTable](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[ProductName] [nvarchar](50) NOT NULL,
	[ProductDesc] [nvarchar](max) NULL,
	[ProductImage] [image] NULL
)

Declaring the connection string for sql connection :
Open App.config and add your connection string to it :


<appSettings>
    <add key="connectionString" value="Data Source=H-PC;Initial Catalog=mydatabase;User ID=sa;Password=123" />
  </appSettings>

Design of the form :

image

Code :


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
using System.IO;
using System.Drawing.Imaging;

namespace Examples
{
    public partial class Products : Form
    {
        SqlConnection con;
        SqlCommand cmd;
        SqlDataReader reader;
        String connectionString = ConfigurationSettings.AppSettings["connectionString"].ToString();
        byte[] imgbyte;

        public Products()
        {
            InitializeComponent();
            display();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtproductname.Text.Trim() == "")
                {
                    MessageBox.Show("Please enter product name ");
                }
                else
                {
                    con = new SqlConnection(connectionString);
                    cmd = new SqlCommand("insert into ProductTable (ProductName, ProductDesc, ProductImage) values (@name,@desc,@img)", con);
                    cmd.Parameters.AddWithValue("@name", txtproductname.Text.ToString());
                    cmd.Parameters.AddWithValue("@desc", txtproductdesc.Text.ToString());
                    cmd.Parameters.AddWithValue("@img", imgbyte);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                    MessageBox.Show("Added Successfully");

                    txtproductname.Text = "";
                    txtproductdesc.Text = "";
                    pictureBox1.Image = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            display();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Title = "Select Image to Upload.";
                dlg.Filter = "Image File (*.jpg;*.bmp;*.gif,*.png)|*.jpg;*.bmp;*.gif;*.png";

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    con = new SqlConnection(connectionString);
                    try
                    {
                        String imageName = dlg.FileName;
                        Bitmap bmp = new Bitmap(imageName);
                        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                        pictureBox1.Image = (Image)bmp;
                        FileStream fstream = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
                        imgbyte = new byte[fstream.Length];
                        fstream.Read(imgbyte, 0, Convert.ToInt32(fstream.Length));
                        fstream.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString());
                    }
                }
            }
        }

        public void display()
        {
            con = new SqlConnection(connectionString);
            cmd = new SqlCommand("select top(1) * from producttable order by id desc", con);
            con.Open();
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                txtname.Text = reader["ProductName"].ToString();
                txtdesc.Text = reader["ProductDesc"].ToString();
                byte[] imagedata = (byte[])reader["ProductImage"];
                MemoryStream memorystream = new MemoryStream(imagedata, 0, imagedata.Length);
                Image image = Image.FromStream(memorystream);
                pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBox2.Image = image;
            }
            else
            {
                txtdesc.Text = "No data found";
            }
            con.Close();
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }
    }
}

image