将图像存储在数据库中

时间:2013-10-14 08:54:31

标签: c# asp.net

我在带有类型文件的输入中显示图像然后我想将此图像保存到数据库。我知道如何将varbinary或图像存储到db但我不知道如何访问输入文件?

SqlConnection con = new SqlConnection(stcon);
        SqlCommand command = new SqlCommand();


            string path = "";
            System.Drawing.Image img = System.Drawing.Image.FromFile(path);
            MemoryStream tmpStream = new MemoryStream();
            img.Save(tmpStream, ImageFormat.Png); // change to other format
            tmpStream.Seek(0, SeekOrigin.Begin);
            byte[] imgBytes = new byte[100000];
            tmpStream.Read(imgBytes, 0, 100000);

            command.CommandText = "INSERT INTO image(image) VALUES (:image)";
            IDataParameter par = command.CreateParameter();
            par.ParameterName = "image";
            par.DbType = DbType.Binary;
            par.Value = imgBytes;
            command.Parameters.Add(par);
            command.ExecuteNonQuery();

3 个答案:

答案 0 :(得分:1)

您只需使用System.IO.File.ReadAllBytes方法读取二进制文件:

byte[] imgBytes = System.IO.File.ReadAllBytes(@"c:\temp\capture.png");

所以在你的情况下你可以这样使用它(替换路径):

string path = @"c:\temp\capture.png";
byte[] imgBytes = System.IO.File.ReadAllBytes(path);

command.CommandText = "INSERT INTO image(image) VALUES (:image)";
IDataParameter par = command.CreateParameter();
par.ParameterName = "image";
par.DbType = DbType.Binary;
par.Value = imgBytes;
command.Parameters.Add(par);
command.ExecuteNonQuery();

答案 1 :(得分:0)

您有http://csharpdotnetfreak.blogspot.com/2009/07/display-images-gridview-from-database.html

的示例

顺便说一句,不要在DB中保存图像,而是保存DB中文件的路径并将图像保存到磁盘。

答案 2 :(得分:0)

根据您的问题,我认为您已将图像插入表中,现在想要检索插入的图像。如果是这样,你可以试试,

                string sql = "";
                string address = "";
                SqlConnection con = new SqlConnection(ConnectionString);
                sql = "SELECT Image from ImageTable where imageId=1";

                DataSet ds = new DataSet();
                SqlCommand cmd = new SqlCommand(sql, con);
                SqlDataAdapter adp = new SqlDataAdapter();
                adp.SelectCommand = cmd;
                adp.Fill(ds,"Data");


                address = "C:\\Users\\CARDIT\\Desktop\\Imag1.jpeg";
                byte[] bytes = (byte[])ds.Tables["Data"].Rows[i][0];
               MemoryStream ms = new MemoryStream(bytes);


               System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

                    Bitmap bmSave = new Bitmap(returnImage);
                    Bitmap bmTemp = new Bitmap(bmSave);

                    Graphics grSave = Graphics.FromImage(bmTemp);
                    grSave.DrawImage(returnImage, 0, 0, returnImage.Width, returnImage.Height);

                    bmTemp.Save(address); //If You want to save in Specific location

                    pictureBox1.Image = bmSave; //if you want to use Image in Picturebox Control;