c# - 有人可以帮助我更好地在 WebForms 中保存图像吗?

标签 c# javascript asp.net

好的,我有一个程序正在播放来自实时网络摄像机的视频,我们称之为“AppVideo”。我有另一个程序要在 webForm 中播放这个视频,我们称这个程序为“播放视频”。

我想在 Play Video 中播放此视频的方式是每隔几秒从 AppVideo 保存一张图像并显示新图像。

所以在 AppVideo 中,我将每个新帧保存到文件流中。

现在我要做的是从该文件流中获取新图像并将其保存在图像文件夹中。这是在播放视频的页面 Video.aspx 中完成的。然后在 viewer.aspx 中显示图像。

这是Video.aspx的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Drawing;

namespace PlayVideo
{
   public partial class Video : System.Web.UI.Page
   {


      protected void Page_Load(object sender, EventArgs e)
      {


        string saveTo = @"C:where to save image";
        FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.ReadWrite);

        using (FileStream fs = File.Open(@"C:filestream is saved", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            ReadWriteStream(fs, writeStream);
        }

        Response.Clear();
        Response.TransmitFile("~/images/test.jpg");



      }

    // readStream is the stream you need to read
    // writeStream is the stream you want to write to
    private void ReadWriteStream(Stream readStream, Stream writeStream)
    {
        int Length = 256;
        Byte[] buffer = new Byte[Length];
        int bytesRead = readStream.Read(buffer, 0, Length);
        // write the required bytes
        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = readStream.Read(buffer, 0, Length);
        }
        readStream.Close();
        writeStream.Close();
    }

   }

}

然后这里是viewer.aspx的代码:

  <head id="Head1" runat="server"> 

  <title></title>   

  <script type="text/javascript" src="refreshImagePage.js"></script>

  </head>

  <body>
  <form id="form1" runat="server">
  <div style="height: 60px" id="div1"> 


 <img src="/Video.aspx" id="the_image" alt="" />


 <script type="text/javascript" language="javascript">
 //    alert(1)
       function refreshImage() {
 //                  alert(2);
              window.location.reload();

 //         objIMG = document.getElementById('the_image');
 //         objIMG.src = objIMG.src.substr(0, objIMG.src.indexOf('&nocache=')); +'&nocache=' + Math.random();
     //        alert(3);
           }




 $(document).ready(function () {
    setInterval(updateImage, 5000);
 })


</script>



</div>
</form>
</body>
</html>

如果您注意到,在 viewer.aspx 的 javascript 中,我正在刷新整个页面并注释掉仅刷新图像。刷新图像不起作用,我认为这是因为图像的保存方式;从文件流中保存图像的功能在页面加载中,因此它仅在加载页面时保存最新图像。我已经为此工作了大约 3 个星期,想不出还有什么可以尝试的。有任何想法吗?这种方式现在有效,但我不喜欢它刷新整个页面。

最佳答案

处理此问题的最佳方法是将问题分为两部分:

  1. 图像提供程序,托管在网络服务器上。目前是Viewer.aspx(我们稍后会讲到)
  2. 位于客户端浏览器上的图像消费者。 Viewer.aspx 的渲染形式。

第 1 部分

我们可以将图像提供程序从 aspx 更改为 HTTP 处理程序

ImageHandler.ashx

<%@ WebHandler Language="C#" CodeBehind="ImageHandler.ashx.cs" Class="TestImageHandler.ImageHandler" %>

ImageHandler.ashx.cs

using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Web;

namespace TestImageHandler
{
    /// <summary>
    ///     Summary description for ImageHandler
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var id = context.Request["id"];
            var iId = 0;
            if (id != null && int.TryParse(id.ToString(CultureInfo.InvariantCulture), out iId))
            {
                try
                {
                    RespondForId(iId, context);
                }
                catch (Exception)
                {
                    ErrorResponse(context);
                }
            }
            else
            {
                DefaultResponse(context);
            }
        }

        private static void DefaultResponse(HttpContext context)
        {
            var tt = File.ReadAllBytes(context.Server.MapPath("~/noId.jpg"));
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(tt);
        }

        private static void ErrorResponse(HttpContext context)
        {
            var tt = File.ReadAllBytes(context.Server.MapPath("~/error.jpg"));
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(tt);
        }

        private void RespondForId(int id, HttpContext context)
        {
            var tt = GetImageBytesForId(id); //File.ReadAllBytes(context.Server.MapPath("~/multcust.png"));
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(tt);
        }

        private static byte[] GetImageBytesForId(int id)
        {
            var b = new Bitmap(200, 200);
            byte[] retBytes;
            using (var g = Graphics.FromImage(b))
            {
                g.DrawRectangle(Pens.BurlyWood, 1, 1, 198, 198);
                using (var arialFontLarge = new Font("Arial", 20))
                {
                    g.DrawString(id.ToString(CultureInfo.InvariantCulture), arialFontLarge, Brushes.Black, 5, 100);
                }

                using (var arialFontSmall = new Font("Arial", 10))
                {
                    g.DrawString(string.Format("{0:yyyyMMdd hhmmssffff}", DateTime.Now), arialFontSmall, Brushes.Black, 5, 5);
                }
                var converter = new ImageConverter();
                retBytes = (byte[])converter.ConvertTo(b, typeof(byte[]));
            }
            return retBytes;
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}

第 2 部分

应用程序的客户端。

index.htm

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>File Swap</title>
    <script language="JavaScript">
        function refreshIt() {
            if (!document.images) return;
            for (var i = 1; i <= 6; i++) {
                document.getElementById("imgcontainer" + i).src = "/imagehandler.ashx?id=" + i + "&rand=" + Math.random();
            }
            setTimeout('refreshIt()', 1000);
        }
    </script>
</head>
    <body onload="setTimeout('refreshIt()',1000)">
        <table>
            <tr>
                <td><img id="imgcontainer1" src="/imagehandler.ashx?id=1" alt="cam image" /></td>
                <td><img id="imgcontainer2" src="/imagehandler.ashx?id=2" alt="cam image" /></td>
            </tr>
            <tr>
                <td><img id="imgcontainer3" src="/imagehandler.ashx?id=3" alt="cam image" /></td>
                <td><img id="imgcontainer4" src="/imagehandler.ashx?id=4" alt="cam image" /></td>
            </tr>
            <tr>
                <td><img id="imgcontainer5" src="/imagehandler.ashx?id=5" alt="cam image" /></td>
                <td><img id="imgcontainer6" src="/imagehandler.ashx?id=6" alt="cam image" /></td>
            </tr>
        </table>
    </body>
</html>

更新 1:更改 ImageHandler.ashx.cs 和 index.htm 以处理多个图像。

可以更改方法 GetImageBytesForId 以根据 Id 返回正确的图像,而不是返回虚拟图像。

关于c# - 有人可以帮助我更好地在 WebForms 中保存图像吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25652497/

相关文章:

javascript - 如何将 JSON 对象中的数组从 javascript 传递到 asp.net mvc Controller 方法?

c# - 寻找一个好的练习来帮助我在多线程方面做得更好

javascript - Jest 测试 typescript 文件语法错误 : "interface is a reserved word in strict mode"

javascript - 带有下拉菜单的 Bootstrap Pill 不起作用

c# - 不明确的调用 asp.net mvc 操作方法

asp.net - 奇怪的! MySQL 更新无法正常工作

c# - 从 3.1.2 版升级到 5.0.3 版后,Entity Framework 核心 Include() 不起作用

c# - 将用户输入与文本文件中的字符串列表进行比较

c# - 跨度和二维数组

javascript - JQuery .scrollTop() and .offset().top issue : how it work? 如何解决?