using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Drawing.Imaging; namespace Test { public partial class Form2 : Form { // 摄像头配置信息 private const string IP = "192.168.100.60"; private const string SNAPSHOT_URI = "/snapshot.jpg"; private const string USER = "admin"; private const string PASSWD = "Yexian.net.168"; // 保存路径 private const string SAVE_DIRECTORY = @"D:\Projects"; private string _authorization; public Form2() { InitializeComponent(); // 确保保存目录存在 if (!Directory.Exists(SAVE_DIRECTORY)) { Directory.CreateDirectory(SAVE_DIRECTORY); } } private void button1_Click(object sender, EventArgs e) { Image image = GetCameraImage(); pictureBox1.Image = image; // 自动保存图像到D:\Projects目录 SaveImageToProjects(image); } /// /// 将图像保存到D:\Projects目录 /// private void SaveImageToProjects(Image image) { try { if (image != null) { // 生成带时间戳的文件名 string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"); string fileName = $"CameraSnapshot_{timestamp}.jpg"; string filePath = Path.Combine(SAVE_DIRECTORY, fileName); // 保存图像 image.Save(filePath, ImageFormat.Jpeg); MessageBox.Show($"图像已保存到:{filePath}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information); System.Diagnostics.Debug.WriteLine($"图像保存成功:{filePath}"); } } catch (Exception ex) { MessageBox.Show($"保存图像失败:{ex.Message}", "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Diagnostics.Debug.WriteLine($"图像保存失败:{ex.Message}"); } } /// /// 手动保存当前显示的图像 /// public void SaveCurrentImage() { if (pictureBox1.Image != null) { SaveImageToProjects(pictureBox1.Image); } else { MessageBox.Show("没有可保存的图像", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private Bitmap GetCameraImage() { string url = "http://" + IP + SNAPSHOT_URI; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Headers.Add("Cache-Control", "no-cache"); request.Headers.Add("Pragma", "no-cache"); if (!string.IsNullOrEmpty(_authorization)) { request.Headers.Add("Authorization", _authorization); } HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (System.Net.WebException ex) { if (ex.Response != null && ((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.Unauthorized) { response = (HttpWebResponse)ex.Response; string authHeader = response.Headers["WWW-Authenticate"]; response.Close(); string realm = ExtractAuthParam(authHeader, "realm"); string nonce = ExtractAuthParam(authHeader, "nonce"); _authorization = GenerateDigestAuthorization(USER, PASSWD, realm, nonce, "GET", SNAPSHOT_URI); request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Headers.Add("Authorization", _authorization); response = (HttpWebResponse)request.GetResponse(); } else { throw; } } byte[] imageData; using (Stream stream = response.GetResponseStream()) using (MemoryStream memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); imageData = memoryStream.ToArray(); } return new Bitmap(new MemoryStream(imageData)); } /// /// 从WWW-Authenticate头中提取参数 /// private string ExtractAuthParam(string authHeader, string paramName) { Regex regex = new Regex(paramName + "=\"([^\"]+)\""); Match match = regex.Match(authHeader); if (match.Success) { return match.Groups[1].Value; } return string.Empty; } /// /// 生成Digest认证的Authorization头 /// private string GenerateDigestAuthorization(string username, string password, string realm, string nonce, string method, string uri) { string ha1 = CalculateMD5(username + ":" + realm + ":" + password); string ha2 = CalculateMD5(method + ":" + uri); string response = CalculateMD5(ha1 + ":" + nonce + ":" + ha2); return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"", username, realm, nonce, uri, response); } /// /// 计算MD5哈希值 /// private string CalculateMD5(string input) { using (MD5 md5 = MD5.Create()) { byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append(hashBytes[i].ToString("x2")); } return sb.ToString(); } } } }