gpt4 book ai didi

asp.net - 如何将 MemoryStream 绑定(bind)到 asp :image control?

转载 作者:行者123 更新时间:2023-12-03 22:48:02 25 4
gpt4 key购买 nike

有没有办法将 MemoryStream 绑定(bind)到 asp:image 控件?

最佳答案

最好的办法是创建一个返回图像的 HttpHandler。然后将asp:Image上的ImageUrl属性绑定(bind)到HttpHandler的url。

这是一些代码。

首先创建HttpHandler:

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class ImageHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.Clear();

if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
{
int id = Int32.Parse(context.Request.QueryString["id"]);

// Now you have the id, do what you want with it, to get the right image
// More than likely, just pass it to the method, that builds the image
Image image = GetImage(id);

// Of course set this to whatever your format is of the image
context.Response.ContentType = "image/jpeg";
// Save the image to the OutputStream
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>Need a valid id</p>");
}
}

public bool IsReusable
{
get
{
return false;
}
}

private Image GetImage(int id)
{
// Not sure how you are building your MemoryStream
// Once you have it, you just use the Image class to
// create the image from the stream.
MemoryStream stream = new MemoryStream();
return Image.FromStream(stream);
}
}

接下来,只需在使用 asp:Image 的 aspx 页面中调用它。
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="myImage" ImageUrl="~/ImageHandler.ashx?id=1" runat="server" />
</div>
</form>
</body>
</html>

就是这样。

关于asp.net - 如何将 MemoryStream 绑定(bind)到 asp :image control?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com