我想在编辑时从数据库中检索图像。
但我希望它显示为其文件路径(之前已上传)。
我的想法是使用 MemoryStream 将 varbinary 转换为 byte[],将 byte[] 转换为图像,将 Image 转换为其文件路径。
有可能吗,有人可以帮我吗
我想在编辑时从数据库中检索图像。
但我希望它显示为其文件路径(之前已上传)。
我的想法是使用 MemoryStream 将 varbinary 转换为 byte[],将 byte[] 转换为图像,将 Image 转换为其文件路径。
有可能吗,有人可以帮我吗
您可以从数据库中获取图像,如下所示。
至于路径,保存图片的时候需要保存在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);