Dhiraj's Blogs Born to code

21May/1128

Image to DataBase and from DataBase to PictureBox control (C#)

Background

I have been asked about that how would you put an image directly into the database rather saving it in a file system, that's number one. Then second one was, how would you show the same image or any other image in the PictureBox control. To answer these question I thought of writing a blog itself rather than giving conceptual answers. So here we go!!!

Summary

This is a step-by-step tutorial for uploading or adding an image directly into the database and viewing any uploaded image in the PictureBox control in Windows Forms Application.

In VB 6.0 there is no way of saving the binary large object (BLOB) into the database pro-grammatically, it only has the option to show the binary image from database to PictureBox. But over here in this article we will use MemoryStream object from System.IO base class to copy an image from the db to directly into the PictureBox control.

In order to perform this tutorial I have used following

- Microsoft Visual Studio 2010
- Microsoft SQL Server 2008 R2 (you can also use the MS Access for this)

Also I can assume that most of guys knows the Visual C# .NET Windows Forms applications, Binary Large Object(BLOB) in databases, ADO.NET data access.

Let's Start

  1. As a first step we have to create a table for storing and retrieving our image(s). So let's create the table first using following query
    CREATE TABLE tblBLOB
    (
        BLOBID INT IDENTITY NOT NULL,
        BLOBData IMAGE NOT NULL
    )

    Note: For SQL Server users please select/create a database before you run this query

    Creating Table

    Creating Table

  2. Next step would be opening the Visual Studio and creating the Windows Forms application project

    Creating Project

    Creating Project

  3. Once the project is created the then default windows form will appear in the design mode. Over here you have to add to buttons and one picture box control using ToolBox toolbar. I have renamed the form to BLOBTestForm. After the design is complete it should ideally look like this
    Form Design

    Form Design

    Note: I have added a small label for displaying some messages. As of now it not visible, once we will the program and do any action it will show you the appropriate message.

  4. Once your form design is complete then in the code behind we have to put some code to make it work. We will start with using statements as follows
    using System.Data.SqlClient;
    using System.IO;
    using System.Drawing.Imaging;
  5. As database is involved we have make the connection string as well. Following declaration we can put it inside the public class BLOBTestForm : System.Windows.Forms.Form class declaration, configure the connection string as per your settings.
    String strConn;
    strConn = @"Data Source=myServer;Initial Catalog=Example;User Id=myUser;Password=myPassword;";
  6. Now all necessary things are done, it's time to add some real code on the Button 1(File to Database) click event. This code will read the local image file using FileStream object and then convert it into byte array and pass it to the database using parameterized Command object. Change the file path as necessary.
    try
    {
         SqlConnection conn = new SqlConnection(strConn);
         SqlCommand sqlCmd = new SqlCommand("INSERT INTO tblBLOB (BLOBData) VALUES (@BLOBData)", conn);
         String sBLOBFilePath = @"D:goal.jpg";//Modify this path as needed.
    
         //Read jpg into file stream, and from there into Byte array.
         FileStream fsBLOBFile = new FileStream(sBLOBFilePath, FileMode.Open, FileAccess.Read);
         Byte[] bytBLOBData = new Byte[fsBLOBFile.Length];
         fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
         fsBLOBFile.Close();
    
         //Create parameter for insert command and add to SqlCommand object.
         SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false,
         0, 0, null, DataRowVersion.Current, bytBLOBData);
         sqlCmd.Parameters.Add(prm);
    
         //Open connection, execute query, and close connection.
         conn.Open();
         sqlCmd.ExecuteNonQuery();
         conn.Close();
         lblMsg.Text = "File imported successfully into the database.";
    }
    catch (Exception ex)
    { MessageBox.Show(ex.Message); }
  7. Now we have added code for file to database, now we will add the code for database to picture box control. You can add the following code to Button 2(Database to PictureBox) click event. This piece of code retrieves the image bytes from tblBLOB table in the database and puts it into the DataSet object, copies the recently uploaded image into byte array and then converts that into the MemoryStream array, finally we will load this MemoryStream into the image property of PictureBox control.
    try
    {
        SqlConnection conn = new SqlConnection(strConn);
        conn.Open();
    
        //Retrieve BLOB from database into DataSet.
        SqlCommand sqlCmd = new SqlCommand("SELECT BLOBID, BLOBData FROM tblBLOB ORDER BY BLOBID", conn);
        SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
        DataSet ds = new DataSet();
        sqlDA.Fill(ds, "tblBLOB");
        int c = ds.Tables["tblBLOB"].Rows.Count;
    
        if (c > 0)
        {   //BLOB is read into Byte array, then used to construct MemoryStream,
            //then passed to PictureBox.
            Byte[] byteBLOBData = new Byte[0];
            byteBLOBData = (Byte[])(ds.Tables["tblBLOB"].Rows[c - 1]["BLOBData"]);
            MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
            pbBLOB.Image = Image.FromStream(stmBLOBData);
            lblMsg.Text = "File read from the database successfully.";
        }
        conn.Close();
    }
    catch (Exception ex)
    { MessageBox.Show(ex.Message); }
  8. Coding is done, let's compile and Run this application, to do so press F5.
  9. Once the our Form will appear you first click on File to Database button. So this will add the file into the database. It will look like this

    File to database

    File to database

  10. Once the label shows successful message then you can click on the Database to PictureBox button. This will load the recently added image from the database to PictureBox control. The final output will look like this

    Database to PictureBox

    Database to PictureBox

That's it.

Download

http://dhirajranka.com/misc/BLOBTest.zip

Comments (28) Trackbacks (0)
  1. Cute twitter bird annoying the crap out of me but great article.

  2. Hi,
    This blog is good for beginners .But how can we upload the user selected images to DB.
    And also how can we displayall in Gridview .

    Cheers,
    Samantha.

  3. i hav tried ur following code but m gettin error {keyword not supported InitialCatalog} plz help me out through dis error.
    thnx

  4. thank you very much
    it is very good topic

  5. Thanxx Dude….
    very much….

  6. thnkzz dude …..but i want to do the same thing in webform (asp.net)…..there is no picture box …..how can i display bytes as an image…..plz help me out of dis

  7. I tried this with access 2010. as access don’t have Image type I used oleObject there. But finally I got a error massage saying Parameter is not valid for this line,
    pbBLOB.Image = Image.FromStream(stmBLOBData);

    What is wrong with me !!! pls help

  8. I have written this code specifically for SQL Server, have not tried with MS Access. If I will find anything I will update my article.

  9. parameter not valid please help

    thankyou

  10. i have done this before but i can’t update the image using c#. Can u help me.?

    • If you will follow the steps given in the article then I don’t think that you will get any error. I will add the project file itself in the article so that it will be helpful for you.

  11. the same way i insert the image, i update the image. but after updating the image i can’t retrieve the image, it says invalid image…

  12. saying Parameter is not valid for this line,
    pbBLOB.Image = Image.FromStream(stmBLOBData);

    i have cheke the code thare is no mistake and your sorce code is not openin in vs2008

  13. Hi Bharat,

    I have created the project in Visual Studio 2010. Upgrade it or open the code in notepad and copy it in your VS 2008 files. Make sure you change the namespace properly.

    Hope this helps!

  14. Greetz,

    Great tut.. But how do i place my lblMsg.Text = “File read from the database successfully.”; on a diff spot..

    Thx in advance..

  15. Actually i when we select file to database button “OpenFileDialog” should come were we can add the image what we want … here only single image is taken from path ..!!
    Can u make it in that way … Please reply

  16. hi there i am very impressed with this. I HAVE tried and tested .works wonders. I have about 200 jpeg images which i need to convert into binary data. each one belogs to a specific questionID. IS THERE A WAY TO HAVE IT DONE AT ONE SHOT. SORRY I AM A NEWBIE AT THS.

  17. yogesh ..tis might help

    String Pic = MySubID.Text;
    String sBLOBFilePath = Pic;

    you need to add a Combobox called MySubID on form. (add collection of the path c:pictures1234jpg)
    you can choose your image there.

  18. Excellent post !!!
    Really made my day.
    Thanx a lot for sharing.

  19. This is very use full article for beginners.
    Same Example Setting the image (Font end) to Bank end Provide them.

  20. Thanks, great article =D

  21. I appreciate your efforts. God richly bless you. AMEN!!!!!

  22. your effort is good.But still I m getting error.’parameter is not valid’.

  23. Wonderful post! We are linking to this particularly
    great post on our website. Keep up the great writing.

  24. How to upload image from picturebox.image to database whose datatype is image?

  25. Create a field in the database with “IMAGE” as datatype and use MemoryStream to convert image bytes of PictureBox.Image to database IMAGE type.

    Hope this helps!

  26. ThankuThankuThankuThankuThankuThankuThanku


Leave a comment


− six = 2

No trackbacks yet.