10

i'm trying to load images from database to a PictureBox. I use these following codes in order to load them to my picture. I've written some code but don't know what I should do for continuing.

Any help will be appreciated.

private void button1_Click(object sender, EventArgs e)
    {
        sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
        cmd = new SqlCommand();
        cmd.Connection = sql;
        cmd.CommandText = ("select Image from Entry where EntryID =@EntryID");
        cmd.Parameters.AddWithValue("@EntryID", Convert.ToInt32(textBox1.Text));
    }
leppie
  • 115,091
  • 17
  • 196
  • 297
aliprogrammer
  • 197
  • 1
  • 4
  • 14

4 Answers4

16

Continue with something like this in the button1_Click:

// Your code first, here.

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])ds.Tables["Images"].Rows[count - 1]["Image"];
    var stream = new MemoryStream(data);
    pictureBox1.Image = Image.FromStream(stream);
} 
Mario S
  • 11,715
  • 24
  • 39
  • 47
  • In my database i marked as allow nulls for Image column. but when i use these codes if there is no picture in the row i will encounter an error – aliprogrammer May 04 '12 at 19:30
  • @aliprogrammer: It is pretty much the same answer I posted in the url before (see sample number 7 in the reference) – GoRoS May 04 '12 at 19:46
  • @aliprogrammer I only gave you some pseudo code to show you a way to load an image from a database in to a PictureBox. You need to do your own error handling specific to your code. Now, I hope the down vote isn't because I answered without error handling, cause that would be a bit wrong =) – Mario S May 04 '12 at 20:19
  • @Mario i didn't vote you down. i vote up. seems like sb else voted you down. – aliprogrammer May 06 '12 at 08:41
  • @aliprogrammer ah, ok. It's to bad the person who voted down didn't give an explanation. Well well. – Mario S May 06 '12 at 11:42
4

Assuming we have a simple database with a table called BLOBTest:

CREATE TABLE BLOBTest
(
BLOBID INT IDENTITY NOT NULL,
BLOBData IMAGE NOT NULL
)

We could retrieve the image to code in the following way:

try
{
    SqlConnection cn = new SqlConnection(strCn);
    cn.Open();

    //Retrieve BLOB from database into DataSet.
    SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);   
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds, "BLOBTest");
    int c = ds.Tables["BLOBTest"].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["BLOBTest"].Rows[c - 1]["BLOBData"]);
        MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
        pictureBox1.Image= Image.FromStream(stmBLOBData);
    } 
    cn.Close();
}
catch(Exception ex)
{MessageBox.Show(ex.Message);}

This code retrieves the rows from the BLOBTest table in the database into a DataSet, copies the most recently added image into a Byte array and then into a MemoryStream object, and then loads the MemoryStream into the Image property of the PictureBox control.

Full reference guide:

http://support.microsoft.com/kb/317701

GoRoS
  • 5,183
  • 2
  • 43
  • 66
0
private void btnShowImage_Click(object sender, EventArgs e)
{
    string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
    Con = new OleDbConnection(@constr);
    Con.Open();
    Com = new OleDbCommand();
    Com.Connection = Con;     
    Com.CommandText = "SELECT Photo FROM PatientImages WHERE Patient_Id =  " + val + " ";
    OleDbDataReader reader = Com.ExecuteReader();
    if (reader.Read())
    {
        byte[] picbyte = reader["Photo"] as byte[] ?? null;
        if (picbyte != null)
        {
            MemoryStream mstream = new MemoryStream(picbyte);
            pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
        {
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
    }
}
GoRoS
  • 5,183
  • 2
  • 43
  • 66
0

HERE IS A TOTAL ANOTHER WAY TO DO SO:

You can simply convert the Image to Text before saving it into DataBase and the then convert it back to the Image after reading it:


public string ImageToStringFucntion(Image img)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] imgBytes = ms.ToArray();
                    string FinalText = Convert.ToBase64String(imgBytes, 0 , imgBytes.Length);

                    return FinalText;
                }
            }
            catch
            {
                return null;
            }
        }

Now you can Insert or Update your Database...

Now Let's consider you want it back:

public Image StringToImage_(string input_)
        {
            try
            {
                byte[] imgBytes = Convert.FromBase64String(input_);
                using (MemoryStream ms = new MemoryStream(imgBytes))
                {
                    Image img = Image.FromStream(ms, true);

                    return img;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

Now you can do as follow:

// Considering you have already pulled your data 
// from database and set it in a DataSet called 'ds',
// and you picture is on the field number [1] of your DataRow

pictureBox1.Image = StringToImage_(ds.Table[0].Rows[0][1].ToString());
Atrin Noori
  • 311
  • 3
  • 12