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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18177351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:28:40  来源:igfitidea点击:

How to display image inside web form from Byte Array with C#

c#asp.netwebforms

提问by octohedron

This is my code, all it does is clear the web page and draw the image, so the rest of the form disappears! I need to show the image inside the form.

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

This is my User Control to display the images:

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

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<Byte[]> ArrayFotos = new List<Byte[]>();
                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<Byte[]> ArrayFotos = new List<Byte[]>();
                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);

            }
        }

I need to find a way that doesnt clear all the page, just draw the image inside the user control.

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

采纳答案by Shire

You could write a page .aspx or a handler maybe .ashx that send the content of the picture back to the browser. You could pass information in the url. Then use the url to this page with an html tag or html control to display it.

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

EDIT: You need to use a Control. You could convert the binary data to base64 and output the content to the html page.

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

I give you an example with an img html tag:

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

<img alt="" src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAsMAAAGhCAIAAAALOi7ZAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgLEhM6PUSGrwAAIABJREFUeNq8vcuSLEmWHKZ6jnlEZt5761Z3T/eAHAICAYRcEALsuOCWPzbzDfwP/gKXWJACoRDCBSkEBgPhADKY7qnu+4wIdztHuThmHh55q2t6ho+SlpaqyMwID3ez89CjqsY//dM//bM/+zMc/pGE3//PT/z09/1I0t/1Rz/x+o9+0I++vv/n8fU/8MW/9U9+9JVvL/v/u1cy86cv5ttfePXKq//8fTfhp+/qT3/oq8v+6V/+Ay/v25/+4X/46nqO"/>

You can also use base64 encoding for image with CSS:

您还可以使用 CSS 对图像使用 base64 编码:

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

To convert into base64 from C# you can use:

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

using System;

and:

和:

Convert.ToBase64String(Foto);

回答by Karl Anderson

Response.Clear();is deleting all the buffered content (i.e. everything in your page).

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

Instead of a user control to display a dynamic image, consider an HTTP handler (.ashx), like this:

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

ImageHandler.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; }
    }
}

Then in your .aspxpage:

然后在您的.aspx页面中:

<asp:Image ID="image1" runat="server" ImageUrl="~/ImageHandler.ashx" />

Note: If you want a specific image, then you can pass a query string (i.e. image ID) to the handler and have the byte array logic account for using the query string value.

注意:如果您想要一个特定的图像,那么您可以将查询字符串(即图像 ID)传递给处理程序,并让字节数组逻辑考虑使用查询字符串值。

回答by Sergey Malyutin

There is also another simple way:

还有一种简单的方法:

  1. On your .aspxpage:

    <asp:Image id="Image1" runat="server"></asp:Image>
    
  2. Then in your CodeBehind file .aspx.cs:

    Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(Foto)
    
  1. 在您的.aspx页面上:

    <asp:Image id="Image1" runat="server"></asp:Image>
    
  2. 然后在您的 CodeBehind 文件中.aspx.cs

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