1

我想知道是否可以使用 httphandler 下载图像,将该图像提供给浏览器,然后再做一次。

我目前可以访问一个 url,该 url 可以从我想继续从中提取的 ip 摄像机中生成快照图像。本质上是无限期地制作快照的幻灯片。

我已经想出了如何下载图像并显示它。由于缺乏更好的术语,下一步将递归地重复该过程。

我当然可以使用来自客户端的 Ajax 调用来做到这一点,但更愿意在服务器上删除处理它。

谢谢,

乍得

using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Web;
using System.Threading;



namespace Something.App_Code
{
class CameraSnapshotHandler : IHttpAsyncHandler
{
    public bool IsReusable { get { return false; } }

    public CameraSnapshotHandler() { }

    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
    {
        SnapshotAsynchOperation asynch = new SnapshotAsynchOperation(cb, context, extraData);
        asynch.StartAsyncWork();
        return asynch;
    }

    public void EndProcessRequest(IAsyncResult result) { }

    public void ProcessRequest(HttpContext context)
    {
        throw new InvalidOperationException();
    }
}

class SnapshotAsynchOperation : IAsyncResult
{
    private bool _completed;
    private Object _state;
    private AsyncCallback _callback;
    private HttpContext _context;

    bool IAsyncResult.IsCompleted { get { return _completed; } }
    WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }
    Object IAsyncResult.AsyncState { get { return _state; } }
    bool IAsyncResult.CompletedSynchronously { get { return false; } }

    public SnapshotAsynchOperation(AsyncCallback callback, HttpContext context, Object state)
    {
        _callback = callback;
        _context = context;
        _state = state;
        _completed = false;
    }

    public void StartAsyncWork()
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);
    }

    private void StartAsyncTask(Object workItemState)
    {
        using (var client = new WebClient())
        {
            // Get Json data
            string username;
            string password;
            using (var credClient = new WebClient())
            {
                dynamic stuff = JObject.Parse(credClient.DownloadString(new Uri("http://www.some-url.com/servicestack/equipment-credentials.json?equipmentId=" + _context.Request.QueryString["id"])));
                username = stuff.Username;
                password = stuff.Password;
            }

            // Wait until we have full buffer before displaying
            _context.Response.BufferOutput = true;
            // Set content type to match
            _context.Response.ContentType = "image/png";

            // Digest Authenticate
            client.Credentials = new NetworkCredential(username, password);

            // Download into bit array
            byte[] content = client.DownloadData("http://some-url/cgi/image.php?type=snapshot");
            // Output stream to client
            _context.Response.OutputStream.Write(content, 0, content.Length);
        }

        _completed = true;
        _callback(this);
    }
}

}

4

0 回答 0