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

发布于 2024-09-15 06:25:24 字数 1434 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

各空 2024-09-22 06:25:24

试试这个方法。当您想要存储图像的字段的类型为byte时,它应该可以工作。
首先,它为图像创建byte[]。然后,它使用 binary 类型的 IDataParameter 将其保存到数据库中。

using System.Drawing;
using System.Drawing.Imaging;
using System.Data;

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

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

using System.Drawing;
using System.Drawing.Imaging;
using System.Data;

    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 ();
        }
    }
家住魔仙堡 2024-09-22 06:25:24

您需要将图像转换为 C# 中的 byte[],然后将数据库列设置为 varbinary(MAX)

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

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

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

长梦不多时 2024-09-22 06:25:24

这是使用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.

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

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.
难忘№最初的完美 2024-09-22 06:25:24

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

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

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:

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

旧故 2024-09-22 06:25:24

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

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.

愁杀 2024-09-22 06:25:24

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

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.

霓裳挽歌倾城醉 2024-09-22 06:25:24

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

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

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

正如其他海报所说,使用 VARBINARY(MAX) 作为存储类型 - IMAGE 已被弃用。

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

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

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

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

山有枢 2024-09-22 06:25:24

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

  • 将 PictureEdit 的“PictureStoreMode”属性更改为 ByteArray:
    当前设置为“默认”
    在此处输入图像描述
  • 将控件的编辑值转换为 bye:
    byte[] newImg = (byte[])pictureEdit1.EditValue;
  • 保存图像:
    this.tbSystemTableAdapter.qry_updateIMGtest(newImg);

再次感谢您。查格伯特

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:

  • Change the PictureEdit's "PictureStoreMode" property to ByteArray:
    it is currently set to "default"
    enter image description here
  • convert the control's edit value to bye:
    byte[] newImg = (byte[])pictureEdit1.EditValue;
  • save the image:
    this.tbSystemTableAdapter.qry_updateIMGtest(newImg);

Thank you again. Chagbert

那支青花 2024-09-22 06:25:24
//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());
//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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文