如何使用C#从字节数组显示Web表单中的图像

这是我的代码,它只是清除网页并绘制图像,所以表格的其余部分消失了! 我需要在表单中显示图像。

这是我的用户控件来显示图像:

protected void Page_Load(object sender, EventArgs e) { if (Session["ObjHoteles"] == null) { Label1.Text = "Por favor, primero seleccione un hotel para desplegar las fotos."; } else { if (!IsPostBack) { List ArrayFotos = new List(); string NombreDelHotel = ""; Hoteles Hotel1 = (Hoteles)Session["ObjHoteles"]; NombreDelHotel = Hotel1.NombreHotel; ArrayFotos = Persistencia.PersistenciaFotos.FotosDeHotel(NombreDelHotel); Session["CantFotos"] = ArrayFotos.Count(); Byte[] Foto = ArrayFotos[0]; Response.Buffer = true; Response.Clear(); Response.ContentType = "image/jpeg"; Response.Expires = 0; Response.BinaryWrite(Foto); Session["NumFoto"] = 0; } else { List ArrayFotos = new List(); string NombreDelHotel = ""; Hoteles Hotel1 = (Hoteles)Session["ObjHoteles"]; NombreDelHotel = Hotel1.NombreHotel; ArrayFotos = Persistencia.PersistenciaFotos.FotosDeHotel(NombreDelHotel); Session["CantFotos"] = ArrayFotos.Count(); Byte[] Foto = ArrayFotos[(int)Session["NumFoto"]]; Response.Buffer = true; Response.Clear(); Response.ContentType = "image/jpeg"; Response.Expires = 0; Response.BinaryWrite(Foto); } } 

我需要找到一种不清除所有页面的方法,只需在用户控件中绘制图像。

您可以编写一个页面.aspx或一个处理程序,可能是.ashx将图片的内容发送回浏览器。 您可以在url中传递信息。 然后使用带有html标记或html控件的URL到该页面来显示它。

编辑:你需要使用一个控件。 您可以将二进制数据转换为base64并将内容输出到html页面。

我给你一个img html标签的例子:

  

您还可以使用带有CSS的图像的base64编码:

 background-image: url(data:image/jpeg;base64,IVB) 

要从C#转换为base64,您可以使用:

 using System; 

和:

 Convert.ToBase64String(Foto); 

还有另一种简单的方法:

  1. .aspx页面上:

      
  2. 然后在你的CodeBehind文件.aspx.cs

     Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(Foto) 

Response.Clear(); 正在删除所有缓冲的内容(即页面中的所有内容)。

而不是用户控件来显示动态图像,考虑HTTP处理程序( .ashx ),如下所示:

ImageHandler.ashx:

 public class ImageHandler : System.Web.IHttpHandler { public void ProcessRequest(HttpContext context) { // Logic to get byte array here byte[] buffer = WhateverLogicNeeded; context.Response.ContentType = "image/jpeg"; context.Response.OutputStream.Write(buffer, 0, buffer.Length); } public bool IsReusable { get { return false; } } } 

然后在.aspx页面中:

  

注意:如果需要特定图像,则可以将查询字符串(即图像ID)传递给处理程序,并使用字节数组逻辑帐户来使用查询字符串值。