有人能帮我在WebForms中保存图像的更好方法吗

本文关键字:图像 保存 更好 方法 WebForms | 更新日期: 2023-09-27 18:20:42

好的,我有一个程序正在播放来自实时ip摄像机的视频,让我们称之为"AppVideo"。我有另一个程序将在webForm中播放此视频,让我们将此程序称为"播放视频"。

我想在"播放视频"中播放此视频的方式是每隔几秒钟从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个星期了,想不出还有什么可以尝试的了。有什么想法吗?这种方式现在有效,但我不喜欢它刷新整个页面。

有人能帮我在WebForms中保存图像的更好方法吗

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

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

第1部分

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

图像处理程序.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返回正确的图像,而不是返回伪图像。