问题
I have binary data in SQL database of images.And there may be multiple records of any single ID.Means there may be multiple images for one ID.
And i have to fetch binary data of images from database and convert into image and bind with image gallery.
I am working on ASP.NET 4.0.
I want to do that without any third party control.
Can any one help me out on this ?
回答1:
you need to write your binary value on response using
HttpContext.Current.Response.BinaryWrite()
first you need to set the ImageUrl attribute of an image element to a empty aspx page, or an ashx handler, as a better choice.
and then send the id of record which has the binary value as querystring to that page, like this:
<asp:Image ID="Image1"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=1' />
and then in code behind of that specific page (ashx handler, in our case) you need to get binary value from your dbase and write to response like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string id = HttpContext.Current.Request.QueryString["imageID"];
var image = GetBinaryImageFromDataBaseByRecordID(id);
context.Response.ContentType = "image/jpeg"; // you need to set this to content-type of your image
context.Response.BinaryWrite(image);
}
private byte[] GetBinaryImageFromDataBaseByRecordID(string ImageRecordID)
{
throw new Exception(); // you need to get binary value from db using ImageRecordID and return;
}
public bool IsReusable
{
get
{
return false;
}
}
}
if you have more than one image for a subject, for example 3 images, you can use 3 image element, and they request to existed handler like this:
<asp:Image ID="Image1"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=1' />
<asp:Image ID="Image2"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=20' />
<asp:Image ID="Image3"
runat="server"
CssClass="w120px h120px"
ImageUrl='ImageHandler.ashx?imageID=30' />
回答2:
you need to have a page, which id of your subject is passed to, then in that page you need to create a DataList or repeater or some other data controls and get a query from db and bind image records of that subject to your control, and create image element in DataList or some other data control, for each record, and set the ImageUrl of image element when your data control DataList, for example is bound, something like this:
<asp:DataList ID="DataList2" runat="server"
RepeatColumns="4"
RepeatDirection="Horizontal">
<ItemTemplate>
<asp:Image ID="Image1"
runat="server"
CssClass="w120px h120px"
ImageUrl="ImageHandler.ashx?imageID=<%# Eval("ID") %>" />
</ItemTemplate>
来源:https://stackoverflow.com/questions/21753880/how-to-bind-image-gallery-with-sql-data-table-in-asp-net