2

我在输入文件中显示图像然后我想将此图像保存到数据库。我知道如何将 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();
4

3 回答 3

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();
于 2013-10-14T09:00:41.437 回答
0

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

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

于 2013-10-14T09:23:54.707 回答
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;
于 2013-10-14T09:26:13.487 回答