Saving picture to Database in c#

Saving image to Database in c#
saving picture to database is simple task. For saving images in database we have to convert image to byte array. And for reading we will reverse this process i-e we will convert back byte arrary to image. lets start by creating new project.
  • Create new windows forms project in visual studio
  • Install package "Entityframework" to your project
  • Create table in database
  • Create stored procedure in database
  • create dbcontext class
  • Create EmployeeModel class
  • create employeeDal class
  • Add windows form to your project with picture box
 








Create table employee
CREATE TABLE [dbo].[Employee](
	[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeName] [varchar](100) NULL,
	[Position] [varchar](100) NULL,
	[EmpCode] [varchar](50) NULL,
	[MobileNo] [varchar](50) NULL,
	[Picture] [image] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
	[EmployeeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Create stored procedure
create proc sp_insert_Employee
@EmployeeName varchar(100),
@Position varchar(100)=null,
@EmpCode varchar(50)=null,
@MobileNo varchar(50)=null,
@Picture image=null
as
INSERT INTO [Employee]
           ([EmployeeName]
           ,[Position]
           ,[EmpCode]
           ,[MobileNo]
           ,[Picture])
     VALUES
           (@EmployeeName,
           @Position, 
           @EmpCode, 
           @MobileNo,
           @Picture)
Add dbContext Class
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
   public class MyDbContext:DbContext
    {
        public MyDbContext():
            base("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=(local);")
            //better to save connection string in app.config
        {

        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}
Add EmployeeModel.cs class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
   public class EmployeeModel
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public string Position { get; set; }
        public string EmpCode { get; set; }
        public string MobileNo { get; set; }
        public byte[] Picture { get; set; }
    }
}
Add EmployeeDAL.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    public class EmployeeDAL
    {
        MyDbContext _db = new MyDbContext();
        public int AddEmployee(EmployeeModel model)
        {
            SqlParameter _name = new SqlParameter("@EmployeeName", model.EmployeeName);
            SqlParameter _position = new SqlParameter("@Position", model.Position);
            SqlParameter _empCode = new SqlParameter("@EmpCode", model.EmpCode);
            SqlParameter _mobileNo = new SqlParameter("@MobileNo", model.MobileNo);
            SqlParameter _picture = new SqlParameter("@Picture", model.Picture);
            int effectedrows = _db.Database.ExecuteSqlCommand("exec sp_insert_Employee @EmployeeName,@Position,@EmpCode,@MobileNo,@Picture",
                _name, _position, _empCode, _mobileNo, _picture);

            return effectedrows;
        }
    }
}
Add required controls to form as show in picture on the top of this page. i-e textboxes, PitureBox and a savebutton
Now add the following two functions to form.cs. don't forget to add namespace using System.IO before adding these functions
   private byte[] ImageToByte(Image img)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, img.RawFormat);
                return ms.ToArray();
            }
        }
        private Image BytesToImage(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                var img = Image.FromStream(ms);
                return img;
            }
        }
now double click on picturebox1 and the following code
   private void pictureBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "jpg files|*.jpg|Png files|*.png";
            if(ofd.ShowDialog()== DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(ofd.FileName);
            }
        }
Now double click the save button and the following code.
  private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtName.Text != "" && pictureBox1.Image != null)
            {
                EmployeeModel model = new EmployeeModel()
                {
                    EmployeeName = txtName.Text,
                    EmpCode = txtEmpCode.Text,
                    MobileNo = txtMobileNo.Text,
                    Position = txtPosition.Text,
                    Picture = ImageToByte(pictureBox1.Image)
                };
                EmployeeDAL employeeDAL = new EmployeeDAL();
                int result = employeeDAL.AddEmployee(model);
                if (result > 0)
                {
                    pictureBox1.Image = null;
                    txtName.Text = "";
                    MessageBox.Show("record saved");
                }
            }
        }
Whole form code should look like the following
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtName.Text != "" && pictureBox1.Image != null)
            {
                EmployeeModel model = new EmployeeModel()
                {
                    EmployeeName = txtName.Text,
                    EmpCode = txtEmpCode.Text,
                    MobileNo = txtMobileNo.Text,
                    Position = txtPosition.Text,
                    Picture = ImageToByte(pictureBox1.Image)
                };
                EmployeeDAL employeeDAL = new EmployeeDAL();
                int result = employeeDAL.AddEmployee(model);
                if (result > 0)
                {
                    pictureBox1.Image = null;
                    txtName.Text = "";
                    MessageBox.Show("record saved");
                }
            }
        }
        private byte[] ImageToByte(Image img)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                img.Save(ms, img.RawFormat);
                return ms.ToArray();
            }
        }
        private Image BytesToImage(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                var img = Image.FromStream(ms);
                return img;
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "jpg files|*.jpg|Png files|*.png";
            if(ofd.ShowDialog()== DialogResult.OK)
            {
                pictureBox1.Image = Image.FromFile(ofd.FileName);
            }
        }
    }
}

Post a Comment