Reputation: 1838
I have a web page with a method called to display some images in the DataList
control
MyImage.cs
class MyImage
{
string Name { get; set; }
byte[] Jpeg { get; set; }
}
MyImages.aspx.cs
public void DisplayMyImages(IEnumerable<MyImage> myImages)
{
this.myImagesDataList.DataSource = myImages;
this.myImagesDataList.DataBind();
}
/// ...
protected void myImagesDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
MyImage myImage = (MyImage)e.Item.DataItem;
Image myImageImage = (Image)e.Item.FindControl("myImageImage");
// How to pass myImage.Jpeg to ImageHandler? form here
myImageImage.ImageUrl = "~/Handlers/ImageHandler.ashx";
}
}
But how to pass jpeg image to ImageHandler
if it is already extracted from the database and passed to DisplayMyImages()
function?
Remarks:
I do not want to save them back to files and pass the paths in a query string to ImageHandler
Having a standard query string approach is not possible as I do not want to violate model view presenter approach
Upvotes: 2
Views: 4041
Reputation: 31198
I've just answered your question on CodeProject, but I'll copy the answer here as well.
Depending on how big your images are, and which browsers you need to support, you might be able to use a data URI.
myImageImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(myImage.Jpeg);
(If you're using IE8, you're limited to 32Kb; earlier versions of IE aren't supported at all.)
Upvotes: 1
Reputation: 8580
First of all i think you may going wrong
myImageImage.ImageUrl = "~/Handlers/ImageHandler.aspx";
NOTE: you need to include ImageHandler file with .ashx
not .aspx
file. .ashx Generic Handler
that works as image on context while retrieving image from ImageHandler. Here is the correct form of ImageHandler file.
imgProfile.ImageUrl = "ImageHandler.ashx?imgid=" + imageId.ToString();
click here to see complete referece.
Hope, It may helps you. !!
Upvotes: 0
Reputation: 12904
It would be much easier to pass in the ID of the image and retrieve this directly from the DB when required and use code similiar to ;
var data = //Code to retrieve byte[];
int len = data.Length;
response.ContentType = "image/png";
response.BinaryWrite(data);
Upvotes: 0
Reputation: 6805
Normaly image should be produced by ImageHandler not passed to, so just flip your logic. You will end up with something like this:
myImageImage.ImageUrl = "~/Handlers/ImageHandler.aspx?id=yourImageId";
Make sure you set correct content type, something like this:
context.Response.ContentType = "image/png";
And this is how you write your image to response:
byte[] fileData = null;
//TODO: load your image data into fileData!
context.Response.BinaryWrite(fileData);
Upvotes: 2