c# - 使用c#在asp.net中显示varbinary图像

标签 c# asp.net image varbinary

所以我有这个方法:

    string sql = string.Format("EXECUTE getPlayerImage @playerID = '{0}'", bio.playerID);


    SqlCommand cm = baseballConnection.CreateCommand();

    baseballConnection.Open();
    cm.CommandText = sql;
    baseballConnection.Close();
    return cm.ExecuteScalar() as byte[];

它有效,至少我没有收到任何错误。但现在我只有一个字节数组,如何在屏幕上显示它?我的屏幕上有一个图像工具,但我知道如何显示图像的唯一方法是将其保存在服务器上并具有文件路径。我不知道如何将字节数组保存到服务器,但这将是很糟糕的,而且我已经将图像作为 varbinary 保存在数据库中然后现在检索它是没有意义的。

我怎样才能显示这个字节数组?

最佳答案

要在 ASP.NET 中呈现图像,您必须创建一个 ASP.NET 页面或通用处理程序来保存输出响应流中的字节。

然后,您可以设置 HTML 图像或控件来链接到页面或通用处理程序。

例如,

<img src="getimage.aspx?id=1" style="width:100px; height:100px" alt="" />

所以在你的情况下,它会是这样的:

using System.Web;

namespace ImageUtil
{
    public class ImageProvider : IHttpHandler
    {
        publicvoid ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";

            string sql = string.Format("EXECUTE getPlayerImage @playerID = '{0}'", bio.playerID);

            SqlCommand cm = baseballConnection.CreateCommand();
            baseballConnection.Open();
            cm.CommandText = sql;
            byte[] img = (byte[])cm.ExecuteScalar();
            baseballConnection.Close();

            context.Response.BinaryWrite(img);
        }

        publicbool IsReusable
        {
            get
            {
                returnfalse;
            }
        }
    }
}

这是一个链接: http://samiradel.wordpress.com/2011/08/03/how-to-display-image-byte-array-in-a-an-img-tag/

关于c# - 使用c#在asp.net中显示varbinary图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16947159/

相关文章:

php图像箭头线需要平滑

android - 裁剪具有特殊框架的图像

c# - 将 Grid.MVC 数据导出到 Excel

c# - 使用 Pulumi 为 Azure 应用程序配置增加值(value)

ASP.NET MVC 2 技术根据用户权限隐藏 View 的一部分

asp.net - 如何将 Kentico 实例复制到本地机器?

c++ - 在 C++ 中计算单 channel 直方图的均值和标准差

c# - 在 C# 中,如何将空检查添加到动态快速代码中

c# - C#-单击按钮时从列表中删除项目

c# - Linq to SQL Where In子句导致对象未设置为对象实例