如何从SQL数据库获取图像文件

问题描述:

我已经将二进制数据从数据库存储到内存流文件中,并且我想在表示层上显示该图像,但是我遇到了问题,

谢谢亲爱的thanx,但我想在页面上显示该图像,所以我应该这样做吗?
这是代码:

i have got the binary data from data base into a memory stream file and i want to display that image on presentation layer but i am facing problem,

thanx for your reply dear but i want to display that image on page so should i do?
here is the code:

<pre lang="cs">protected void Page_Load(object sender, EventArgs e)
   {
       con = new SqlConnection(@"data source=MRBALOCH-PC\SQLEXPRESS;initial catalog=test;integrated security=true");
       cmd = new SqlCommand("select * from Gallery", con);
        if (!Page.IsPostBack)
       {
           cmd.Connection.Open();
           rd = cmd.ExecuteReader();
           GridView1.DataSource = rd;
           GridView1.DataBind();
           cmd.Connection.Close();
           //MemoryStream ms = null;
           System.Drawing.Image FullsizeImage = null;
           foreach (GridViewRow r in GridView1.Rows)
           {
               cmd = new SqlCommand("select Picture from Gallery", con);
               cmd.Connection.Open();
               byte[] ImageData = (Byte[])cmd.ExecuteScalar();
              using (MemoryStream ms=new MemoryStream (ImageData ))
              {
                  using (System .Drawing .Image img=System .Drawing .Image .FromStream (ms))
                  {
                      img.Save("naseer", System.Drawing.Imaging.ImageFormat.Jpeg);
                  }
              }
               cmd.Connection.Close();
           }
       }


}


}

回应您对dmageiras的回答的评论.

可以从Image创建Bitmap(如果您想知道如何操作,请在MSDN上查找位图构造函数).我确信您熟悉并可以使用位图.

用你的大脑和一个搜索引擎,我相信你会找到解决方案的.
In response to your comment on dmageiras''s answer.

A Bitmap can be created from an Image (If you want to know how, then look up the bitmap constructor on MSDN). A Bitmap is something that I am sure that you are familiar with and can make use of.

Apply your brain and a search engine and I''m sure that you will find a solution.


将此代码添加到您的方法中:

Add this code to your method:

using (MemoryStream ms = new MemoryStream(ImageData))
{
    using (Image img = Image.FromStream(ms))
    {
        // do whatever you want with image object
        // for example, save it to disk like this:
        img.Save(filename, ImageFormat.Jpeg);
    }
}



希望对您有所帮助.



Hope this helps.


您是否看到过 Image.FromStream() [ ^ ]方法?
Have you seen the Image.FromStream()[^] method?