是否有可能将varbinary图像转换为C#中的文件路径?

时间:2013-05-30 05:50:16

标签: c#

我想在编辑时从数据库中检索图像。

但我希望它显示为文件路径(之前已上传)。

我的想法是使用MemoryStream和Image将varbinary转换为byte [],byte []为image到其文件路径..

是否有可能,任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

您可以从db获取图像,如下所示 至于路径,您需要在保存图像时将其保存在数据库中。

public void GetImage(string strSQL)
{

    using( System.Data.IDbConnection con = new System.Data.SqlClient.SqlConnection("constring"))
    {

        lock (con)
        {

            using (System.Data.IDbCommand cmd = con.CreateCommand())
            {

                lock (cmd)
                {

                    cmd.CommandText = strSQL;

                    if (con.State != System.Data.ConnectionState.Open)
                        con.Open();

                    using (System.Data.IDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess))
                    {
                        lock (reader)
                        {
                            int i = reader.GetOrdinal("Field1");

                            byte[] baImage;
                            System.Drawing.Image img;
                            using (var ms = new System.IO.MemoryStream())
                            {
                                byte[] buffer = new byte[8040]; // sql page size
                                int read;
                                long offset = 0;
                                while ((read = (int)reader.GetBytes(i, offset, buffer, 0, buffer.Length)) > 0)
                                {
                                    ms.Write(buffer, 0, read);
                                    offset += read; // oops! added this later... kinda important
                                } // Whend

                                baImage = ms.ToArray(); // Here's your image as byte array
                                img = System.Drawing.Image.FromStream(ms); // Here's your image as image
                            } // End Using ms

                        } // End Lock reader

                    } // End Using reader

                } // End Lock cmd

            } // End Using cmd

        } // End Lock con

    } // End using con

} // End Sub GetImage

如果要在网站上显示图像,可以这样做(在新的通用处理程序的处理请求中):

System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType("image/jpeg");
System.Web.HttpContext.Current.Response.BinaryWrite(baImage);