How to convert an Array of Bytes to a Direct Image in Listview?

Asked

Viewed 718 times

3

I populated THE Datasource of Listview with a collection. The collection contains a field with ArrayBytes. I need to convert to the image appear in control. But the conversion has to be direct in control?

<ItemTemplate>
    <h2><%#Eval("titulo")%></h2>                                                  
    <p><h5><%#Eval("texto")%></h5></p>                    
    <h6><%#Eval("data", "{0:d}")%></h6>
    **CONVERSÃO AQUI**  

  • Give more details, show what you’ve done, what your difficulty is.

1 answer

1

Base class for the two 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

To make the conversion you must encode into 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 put an Image element (<asp:image) and pass an equal path is 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 insert an item called Generic Handler

inserir a descrição da imagem aqui

and encode it like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Img.Db;
namespace Img.WebForms
{
    /// <summary>
    /// Summary description for _handler
    /// </summary>
    public class _handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //Recupero a Id daquele registro
            Int32 Id = 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 this line is would be the access part to the bank:

Imagens img = new AppEntities().Imagens.Find(Id);

I take this class which has the Image type field Array de Bytes and goes 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 picture field.

A good read would be on this link: ASP . NET - Using an ASHX handler (Handler), has a good explanation of the subject.

2) Webmvc

For Webmvc changes a little the coding, but, would be like this:

Create a method in any 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;
}

Go to View and 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>
  • I couldn’t do it. thanks for the help. great content. I’ll keep trying. Maybe I couldn’t explain my difficulty.

  • Explain your difficulty @dezoldan ?

  • yes, thank you. I’ll try.

  • I am trying to convert an array of bytes into an image directly in control. The difficulty would be this. sorry for the lack of more technical explanation.

  • @dezoldan to show the image is this way, including all use it like this. In the specific controller has nothing ready.

  • I’ll try as you explain @Cezar

  • could not implement as you explained, unfortunately. I would like to take a look at my project, to help me?

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.