Base class that serves both examples:
namespace Img.Db
{
using System;
using System.Collections.Generic;
public partial class Imagens
{
public int Id { get; set; }
public byte[] Imagem { get; set; }
public string Tipo { get; set; }
}
}
1) WebForms
In order to do the conversion you must code in a file Generic Handler
( .ashx
, this type of extension is a page that only has code) and put in your item like this:
In the tag place an Image element ( <asp:image
) and pass an equal path in the example:
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<h2><%#Eval("titulo")%></h2>
<p><h5><%#Eval("texto")%></h5></p>
<h6><%#Eval("data", "{0:d}")%></h6>
<asp:Image ImageUrl='<%#String.Format("_handler.ashx?id={0}", Eval("id")) %>' runat="server" />
</ItemTemplate>
</asp:ListView>
Go to your project and enter an item called Generic Handler
andencodeitlikethis:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingImg.Db;namespaceImg.WebForms{///<summary>///Summarydescriptionfor_handler///</summary>publicclass_handler:IHttpHandler{publicvoidProcessRequest(HttpContextcontext){//RecuperoaIddaqueleregistroInt32Id=Int32.Parse(context.Request["id"].ToString());
//Recupero com o Id a classe que contem o campo Imagem (Array de Bytes)
Imagens img = new AppEntities().Imagens.Find(Id);
//Passo aqui o tipo da imagem para o ContentType
context.Response.ContentType = img.Tipo;
//Passo aqui a imagem no formato array para ele fazer a conversão
context.Response.OutputStream.Write(img.Imagem, 0, img.Imagem.Length);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Where is this line would be the access part of the bank:
Imagens img = new AppEntities().Imagens.Find(Id);
I get this class which has the Image field of type Array de Bytes
and passes to the lines just below the code ( Imagens img = new AppEntities().Imagens.Find(Id);
) and it will return me an image to be shown in a field image.
A good read would be on this link: ASP.NET - Using an ASHX Handler , has a good explanation of the subject.
2) WebMvc
For WebMvc it changes the coding a bit, but, it would look like this:
Create a method in some controller
:
public FileContentResult Display(int Id)
{
Imagens img = db.Imagens.Find(Id);
if (img != null)
{
Byte[] _bytes = img.Imagem;
return new FileContentResult(_bytes, img.Tipo);
}
return null;
}
In the View you will render the image:
@model IEnumerable<Img.Db.Imagens>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Fotos</h2>
<form action="/Fotos/Index" method="post" enctype="multipart/form-data">
<input type="file" name="imagem" id="imagem" />
<button type="submit">Enviar</button>
</form>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Tipo)
</th>
<th>Fotos</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Tipo)
</td>
<td>
<img src="@Url.Action("Display","Fotos", new {Id = item.Id})" width="100" />
</td>
</tr>
}
</table>