Thursday, June 24, 2010

How to store Image in binary format using Linq ?

In the below example I will show how we can convert the image into binary and store it in a database.
In the example when 'Submit' button is clicked the image is copied from FileUpload control and stored in the database in Binary format.

Please follow the code below for more information.

protected void btnSubmit_Click(object sender, EventArgs e)

{

     //fileUploadImg is a FileUpload control.

     if (fileUploadImg.HasFile && fileUploadImg.PostedFile.ContentLength > 0)

     {

        //Get the image in byte’s

        byte[] fileByte = fileUploadImg.FileBytes;

        System.Data.Linq.Binary fileBinary = new  System.Data.Linq.Binary(fileByte);

        MovieTable movie = new MovieTable();

        movie.Director = txtDirector.Text;

        movie.Title = txtTitle.Text;

        //Make sure this column accepts binary.

        movie.Photo = fileBinary;

        //Add to the data context.

        MovieDataContext db = new MovieDataContext();

        db.MovieTables.InsertOnSubmit(movie);

        db.SubmitChanges();

     }

}

No comments:

Post a Comment