当与图像站点的连接不是私有时,如何加载图片框图像?

问题描述 投票:2回答:1

我有一个由ONVIF ip摄像头给出的链接,其中包含由所述摄像头拍摄的快照。

当我尝试在Chrome之类的浏览器上打开此链接时,我收到以下提示:

Your connection to this site is not private

当我尝试从c#windows窗体图片框中加载此图像时,出现以下错误:

加载:

picturebox0.Load(mySnapUrl);

错误:

System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'

输入相应的用户名和密码后,我可以在浏览器中看到该图像。

有什么方法可以在图片框中加载这样的图像吗?

编辑1:

我尝试this solution手动加载图像在Web客户端上,我手动添加凭据,我仍然在downloadData线上得到相同的错误。

WebClient wc = new WebClient();
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(mySnapUrl), "Basic", new NetworkCredential(user, password));
wc.Credentials = cc;
MemoryStream imgStream = new MemoryStream(wc.DownloadData(mySnapUrl));//Error
picturebox0.Image = new System.Drawing.Bitmap(imgStream);
c# picturebox onvif
1个回答
3
投票

正如@Simon Mourier和@Reza Aghaei在评论中所说的那样,我不需要添加CredentialCache但只需添加Credentials。解决方案类似于this one

解:

WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(user, password);
MemoryStream imgStream = new MemoryStream(wc.DownloadData(mySnapUrl));//Good to go!
picturebox0.Image = new System.Drawing.Bitmap(imgStream);

编辑:

我个人必须能够异步加载所述图像,因为我曾经用picturebox0.LoadAsync(mySnapUrl)加载我的图像。

我从这个source得到了很大的想法。

为了能够与需要凭证的图像相同,我创建了一个async Task来加载图像......

private async Task<Image> GetImageAsync(string snapUrl, string user, string password)
{
    var tcs = new TaskCompletionSource<Image>();

    Action actionGetImage = delegate ()
    {
        WebClient wc = new WebClient();
        wc.Credentials = new NetworkCredential(user, password);
        MemoryStream imgStream = new MemoryStream(wc.DownloadData(snapUrl));
        tcs.TrySetResult(new System.Drawing.Bitmap(imgStream));
    };

    await Task.Factory.StartNew(actionGetImage);

    return tcs.Task.Result;
}

...然后使用以下内容设置图像:

var result = GetImageAsync(mySnapUrl, user, password);
result.ContinueWith(task =>
{
    picturebox0.Image = task.Result;
});
© www.soinside.com 2019 - 2024. All rights reserved.