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

r.r*_*r.r 28 c# sql asp.net-mvc ado.net

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

jet*_*hro 23

试试这个方法.当你想要存储图像的字段是类型时它应该工作byte.首先,它创造byte[]了图像.然后它使用IDataParameter类型保存它的DB 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 ();
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 对于那些稍后阅读的人,`DbType.Binary`处理`varbinary(MAX)`,即使帮助工具提示说它限制为8000字节. (3认同)

Mik*_* M. 6

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

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


Abe*_*ler 6

这是一个在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.
Run Code Online (Sandbox Code Playgroud)


Dav*_*sky 4

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

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