将图像存储在数据库中

本文关键字:数据库 存储 图像 | 更新日期: 2023-09-27 18:35:18

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

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();

将图像存储在数据库中

您可以简单地使用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();

你有例子在 http://csharpdotnetfreak.blogspot.com/2009/07/display-images-gridview-from-database.html

顺便说一句,不要将图像保存在数据库中

,而是将文件的路径保存在数据库中并将图像保存到磁盘。

有了您的问题,我认为您已将图像插入表中,现在想要检索插入的图像。 如果是这样,那么您可以尝试为

                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;