如何使用C#在数据库中保存图像

时间:2021-07-24 21:21:13

I want to save user image into a database in C#. How do I do that?

我想将用户图像保存到C#中的数据库中。我怎么做?

9 个解决方案

#1


2  

You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:

您需要将映像序列化为可以存储在SQL BLOB列中的二进制格式。假设你正在使用SQL Server,这里有一篇关于这个主题的好文章:

http://www.eggheadcafe.com/articles/20020929.asp

http://www.eggheadcafe.com/articles/20020929.asp

#2


18  

Try this method. It should work when field when you want to store image is of type bytea. First it creates byte[] for image. Then it saves it DB using IDataParameter of type binary.

试试这个方法。当你想存储图像的字段是bytea类型时它应该工作。首先,它为图像创建byte []。然后使用二进制类型的IDataParameter将其保存为DB。

    public static void PerisitImage(string path, IDbConnection connection)
    {
        using (var command = connection.CreateCommand ())
        {
            Image img = 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[MAX_IMG_SIZE];
            tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

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

#3


5  

You'll want to convert the image to a byte[] in C#, and then you'll have the database column as varbinary(MAX)

你想要将图像转换为C#中的byte [],然后你将数据库列作为varbinary(MAX)

After that, it's just like saving any other data type.

之后,它就像保存任何其他数据类型一样。

#4


3  

This is a method that uses a FileUpload control in asp.net:

这是一个在asp.net中使用FileUpload控件的方法:

byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.

#5


2  

you can save the path of the image in the database or save the image itself as a BLOB ( binary - array of bytes)..it depends on the case you got,if your application is a web application,then saving the path of the image is much better.but if you got a client based application that connects to a centralized database,then you must save it as binary.

你可以保存数据库中的图像路径或将图像本身保存为BLOB(二进制 - 字节数组)..它取决于你得到的情况,如果你的应用程序是一个Web应用程序,然后保存的路径image要好得多。但是如果你有一个连接到集中式数据库的基于客户端的应用程序,那么你必须将它保存为二进制文件。

#6


2  

My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.

我个人的偏好是不将图像保存到数据库中。将图像保存在文件系统中的某个位置,并将引用保存在数据库中。

#7


1  

Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.

由于您使用的是SQL,因此建议不要使用adhoc('在字符串中编写语句'),特别是考虑到您正在加载图像。

ADO.NET can do all of the hard work of mapping, escaping etc for you.

ADO.NET可以为您完成映射,转义等所有艰苦工作。

Either create a Stored Procedure, or use SqlParameter to do the binding.

创建存储过程,或使用SqlParameter进行绑定。

As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.

正如其他海报所说,使用VARBINARY(MAX)作为您的存储类型 - 图像被删除。

#8


-1  

I think this valid question is already answered here. I have tried it as well. My issue was simply using picture edit (from DevExpress). and this is how I got around it:

我认为这个有效的问题已在这里得到解答。我也试过了。我的问题只是使用图片编辑(来自DevExpress)。这就是我如何解决它:

  • Change the PictureEdit's "PictureStoreMode" property to ByteArray: it is currently set to "default" 如何使用C#在数据库中保存图像
  • 将PictureEdit的“PictureStoreMode”属性更改为ByteArray:它当前设置为“default”
  • convert the control's edit value to bye: byte[] newImg = (byte[])pictureEdit1.EditValue;
  • 将控件的编辑值转换为bye:byte [] newImg =(byte [])pictureEdit1.EditValue;
  • save the image: this.tbSystemTableAdapter.qry_updateIMGtest(newImg);
  • 保存图片:this.tbSystemTableAdapter.qry_updateIMGtest(newImg);

Thank you again. Chagbert

再次感谢你。 Chagbert

#9


-5  

//Arrange the Picture Of Path.***

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

                    string[] PicPathArray;
                    string ArrangePathOfPic;

                    PicPathArray = openFileDialog1.FileName.Split('\\');

                    ArrangePathOfPic = PicPathArray[0] + "\\\\" + PicPathArray[1];
                    for (int a = 2; a < PicPathArray.Length; a++)
                    {
                        ArrangePathOfPic = ArrangePathOfPic + "\\\\" + PicPathArray[a];
                    }
               }

// Save the path Of Pic in database

                    SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                    con.Open();

                    SqlCommand cmd = new SqlCommand("insert into PictureTable (Pic_Path) values (@Pic_Path)", con);
                    cmd.Parameters.Add("@Pic_Path", SqlDbType.VarChar).Value = ArrangePathOfPic;

                    cmd.ExecuteNonQuery();

***// Get the Picture Path in Database.***

SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                con.Open();

                SqlCommand cmd = new SqlCommand("Select * from Pic_Path where ID = @ID", con);

                SqlDataAdapter adp = new SqlDataAdapter();
                cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value = "1";
                adp.SelectCommand = cmd;

                DataTable DT = new DataTable();

                adp.Fill(DT);

                DataRow DR = DT.Rows[0];
                pictureBox1.Image = Image.FromFile(DR["Pic_Path"].ToString());

#1


2  

You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:

您需要将映像序列化为可以存储在SQL BLOB列中的二进制格式。假设你正在使用SQL Server,这里有一篇关于这个主题的好文章:

http://www.eggheadcafe.com/articles/20020929.asp

http://www.eggheadcafe.com/articles/20020929.asp

#2


18  

Try this method. It should work when field when you want to store image is of type bytea. First it creates byte[] for image. Then it saves it DB using IDataParameter of type binary.

试试这个方法。当你想存储图像的字段是bytea类型时它应该工作。首先,它为图像创建byte []。然后使用二进制类型的IDataParameter将其保存为DB。

    public static void PerisitImage(string path, IDbConnection connection)
    {
        using (var command = connection.CreateCommand ())
        {
            Image img = 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[MAX_IMG_SIZE];
            tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);

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

#3


5  

You'll want to convert the image to a byte[] in C#, and then you'll have the database column as varbinary(MAX)

你想要将图像转换为C#中的byte [],然后你将数据库列作为varbinary(MAX)

After that, it's just like saving any other data type.

之后,它就像保存任何其他数据类型一样。

#4


3  

This is a method that uses a FileUpload control in asp.net:

这是一个在asp.net中使用FileUpload控件的方法:

byte[] buffer = new byte[fu.FileContent.Length];
Stream s = fu.FileContent;
s.Read(buffer, 0, buffer.Length);
//Then save 'buffer' to the varbinary column in your db where you want to store the image.

#5


2  

you can save the path of the image in the database or save the image itself as a BLOB ( binary - array of bytes)..it depends on the case you got,if your application is a web application,then saving the path of the image is much better.but if you got a client based application that connects to a centralized database,then you must save it as binary.

你可以保存数据库中的图像路径或将图像本身保存为BLOB(二进制 - 字节数组)..它取决于你得到的情况,如果你的应用程序是一个Web应用程序,然后保存的路径image要好得多。但是如果你有一个连接到集中式数据库的基于客户端的应用程序,那么你必须将它保存为二进制文件。

#6


2  

My personal preference is not to save the images to a database as such. Save the image somewhere in the file system and save a reference in the database.

我个人的偏好是不将图像保存到数据库中。将图像保存在文件系统中的某个位置,并将引用保存在数据库中。

#7


1  

Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.

由于您使用的是SQL,因此建议不要使用adhoc('在字符串中编写语句'),特别是考虑到您正在加载图像。

ADO.NET can do all of the hard work of mapping, escaping etc for you.

ADO.NET可以为您完成映射,转义等所有艰苦工作。

Either create a Stored Procedure, or use SqlParameter to do the binding.

创建存储过程,或使用SqlParameter进行绑定。

As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.

正如其他海报所说,使用VARBINARY(MAX)作为您的存储类型 - 图像被删除。

#8


-1  

I think this valid question is already answered here. I have tried it as well. My issue was simply using picture edit (from DevExpress). and this is how I got around it:

我认为这个有效的问题已在这里得到解答。我也试过了。我的问题只是使用图片编辑(来自DevExpress)。这就是我如何解决它:

  • Change the PictureEdit's "PictureStoreMode" property to ByteArray: it is currently set to "default" 如何使用C#在数据库中保存图像
  • 将PictureEdit的“PictureStoreMode”属性更改为ByteArray:它当前设置为“default”
  • convert the control's edit value to bye: byte[] newImg = (byte[])pictureEdit1.EditValue;
  • 将控件的编辑值转换为bye:byte [] newImg =(byte [])pictureEdit1.EditValue;
  • save the image: this.tbSystemTableAdapter.qry_updateIMGtest(newImg);
  • 保存图片:this.tbSystemTableAdapter.qry_updateIMGtest(newImg);

Thank you again. Chagbert

再次感谢你。 Chagbert

#9


-5  

//Arrange the Picture Of Path.***

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

                    string[] PicPathArray;
                    string ArrangePathOfPic;

                    PicPathArray = openFileDialog1.FileName.Split('\\');

                    ArrangePathOfPic = PicPathArray[0] + "\\\\" + PicPathArray[1];
                    for (int a = 2; a < PicPathArray.Length; a++)
                    {
                        ArrangePathOfPic = ArrangePathOfPic + "\\\\" + PicPathArray[a];
                    }
               }

// Save the path Of Pic in database

                    SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                    con.Open();

                    SqlCommand cmd = new SqlCommand("insert into PictureTable (Pic_Path) values (@Pic_Path)", con);
                    cmd.Parameters.Add("@Pic_Path", SqlDbType.VarChar).Value = ArrangePathOfPic;

                    cmd.ExecuteNonQuery();

***// Get the Picture Path in Database.***

SqlConnection con = new SqlConnection("Data Source=baqar-pc\\baqar;Initial Catalog=Prac;Integrated Security=True");
                con.Open();

                SqlCommand cmd = new SqlCommand("Select * from Pic_Path where ID = @ID", con);

                SqlDataAdapter adp = new SqlDataAdapter();
                cmd.Parameters.Add("@ID",SqlDbType.VarChar).Value = "1";
                adp.SelectCommand = cmd;

                DataTable DT = new DataTable();

                adp.Fill(DT);

                DataRow DR = DT.Rows[0];
                pictureBox1.Image = Image.FromFile(DR["Pic_Path"].ToString());