Displaying images from collection in asp.net
I have a collection of custom type which is as follows:
[DataContract]
public class PhotoDC
{
public PhotoDC();
[DataMember]
public byte[] ImagebyteArray { get; set; }
[DataMember]
public string Name { get; set; }
}
I want to show all the items (image and name) on a web form , any idea which control I can use and开发者_开发技巧 how can I convert byte array to image ?
There is no built-in control in ASP.NET that you can directly assign a byte array to display images. What you can do is, simply write a custom HttpHandler that takes "Name" as an argument and sends the byte array as a binary response to the client with appropriate http response headers.
Here is an example of custom http handler. In this sample image is built from a file using a file stream.
I would use a Repeater
control that has a label and Image controls with the Item template.
The following converts to and from and byteArray.
/// <summary>
/// Converts an Image to Byte array
/// </summary>
/// <param name="imageIn">Image to convert</param>
/// <returns>byte array</returns>
public static byte[] ImageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
/// <summary>
/// Converts an Byte array to and Image
/// </summary>
/// <param name="byteArrayIn">byre array</param>
/// <returns>Image</returns>
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
var returnImage = Image.FromStream(ms);
return returnImage;
}
This link shows you have to bind Memory stream to asp.net image control.
精彩评论