简体   繁体   English

使用C#从SQL Server数据库保存和检索图像

[英]Saving and retrieving of images from SQL Server database using c#

I have created a web page where I have used Image control to display the image. 我创建了一个网页,在其中使用了“ Image控件来显示图像。 Along with this control I have some labels and input box also 除了这个控件,我还有一些标签和输入框

Below is the code which I have used to save the image to database 下面是我用来将图像保存到数据库的代码

byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

SqlParameter UploadedImage = new SqlParameter("@image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;

string sql = "insert into imageDB(Image) values (@image)";

using (SqlCommand cmd = new SqlCommand(sql, conn))
{
   cmd.Parameters.Add(UploadedImage);
   cmd.ExecuteNonQuery();
}

and below is the code I have used to retrieve the image from database 下面是我用来从数据库检索图像的代码

byte[] rawImg = (byte[])rdr["image"];
MemoryStream Stream = new MemoryStream();
Stream.Write(rawImg, 0, rawImg.Length);
Bitmap Display_Picture = new Bitmap(Stream);
//after this no idea how to proceed

I have read some links all are suggesting we can not set this byte information to Image control. 我已经阅读了一些链接,所有都表明我们不能将此字节信息设置为Image control。

Let me know if my way of retrieving the image from data base is right, if its right, what type of control I should use, so that image which has been retrieved from database can be displayed on web page 让我知道我从数据库检索图像的方法是否正确,如果正确,则应使用哪种控件类型,以便已从数据库检索到的图像可以显示在网页上

Is my way of retrieving the image from database right? 我从数据库检索图像的方法正确吗?

I would use the following code instead (sorry not tested): 我会改用以下代码(对不起,未经测试):

byte[] imageBytes = Convert.FromBase64String(rdr["image"]);
MemoryStream stream = new MemoryStream(imageBytes);
Image image = Image.FromStream(stream);

How do I bind the image to an asp.net image control? 如何将图像绑定到asp.net图像控件?

I would create an HttpHandler which gets and returns the image. 我将创建一个HttpHandler来获取并返回图像。 Then bind the ImageUrl property on the asp:Image to the url of the HttpHandler. 然后将asp:Image上的ImageUrl属性绑定到HttpHandler的URL。 How you can do this you can see in the answer of Dale Ragan over here: How to bind a MemoryStream to asp:image control? 如何做到这一点,您可以在Dale Ragan的答案中看到: 如何将MemoryStream绑定到asp:image控件?

First, in your example your have to reset the Position inside your stream to 0: Stream.Position = 0; 首先,在您的示例中,必须将流中的Position重置为0: Stream.Position = 0;

Second, you have to write your image to a local cache folder of your web service that is part of your web application. 其次,您必须将映像写入Web应用程序中Web服务的本地缓存文件夹中。 You image control can have a Source-reference (img.src) to the address of that image. 您的图像控件可以具有该图像地址的Source-reference(img.src)。

Or... you can create an AXD-file / HttpHandler. 或者...您可以创建一个AXD文件/ HttpHandler。 An AXD file is a file, just like an ASPX, but specialized in returning any type of data, like an image. AXD文件是类似于ASPX的文件,但是专门用于返回任何类型的数据(例如图像)。

For more info, see: http://blog.kurtschindler.net/post/using-httphandlers-to-serve-image-files 有关更多信息,请参见: http : //blog.kurtschindler.net/post/using-httphandlers-to-serve-image-files

To retrieve image, and show on asp.net Image control, you can 要检索图像并在asp.net上显示图像控件,您可以

    cn.Open();
    SqlCommand cm = new SqlCommand("select * from ImageCollection where img_id='" + DropDownList1.SelectedItem.ToString() + "'", cn);
    SqlDataAdapter da = new SqlDataAdapter(cm);
    SqlDataReader dr = cm.ExecuteReader();
    try
    {
        if (dr.Read())
        {

            string image1 = Convert.ToString(DateTime.Now.ToFileTime());
            FileStream fs1 = new FileStream(image1, FileMode.CreateNew, FileAccess.Write);
            byte[] bimage1 = (byte[])dr["passport_photo"];
            fs1.Write(bimage1, 0, bimage1.Length - 1);
            fs1.Flush();
            Image1.ImageUrl = "~/images/"+DropDownList1.SelectedItem.ToString();
        }
        dr.Close();
        cn.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }

Alternative solution: 替代解决方案:

Implement a handler to serve the image. 实现一个处理程序来提供图像。 Have a look at the System.Web.IHttpHandler interface. 看一下System.Web.IHttpHandler接口。

The idea would be to write an image tag in your page along the lines of: 想法是按照以下方式在页面中写一个图像标签:

<asp:image runat="server" imageurl="~/Image.ashx?ID=xxx" />

Then in your handler implementation, get the id from the querystring, retrieve the image as you're already doing and then write directly to the response stream. 然后在您的处理程序实现中,从查询字符串获取ID,在执行操作时检索图像,然后直接写入响应流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM