Coded UI C#:如何将捕获的图像直接上传至Azure存储容器
直接上传Coded UI捕获的图像到Azure存储(无需本地保存)
刚好做过类似的需求,核心就是把捕获到的Image对象转换成内存流,直接传给Azure Blob存储的UploadFromStream方法,完全不用落地到本地磁盘。结合你已有的代码,完整实现如下:
完整代码示例
// 必要的命名空间 using System.Drawing; using System.Drawing.Imaging; using System.IO; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; // 捕获Coded UI图像(你的原有代码) BrowserWindow window = new BrowserWindow(); Image cml1 = window.CaptureImage(); // 连接Azure存储并上传图像 string storageConnectionString = "你的Azure存储连接字符串"; if (CloudStorageAccount.TryParse(storageConnectionString, out CloudStorageAccount storageAccount)) { // 获取Blob容器引用 CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("testresult"); container.CreateIfNotExists(); // 生成唯一的Blob文件名(避免重复覆盖) string blobFileName = $"screenshot_{DateTime.Now:yyyyMMddHHmmssfff}.png"; CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobFileName); // 将Image转换为内存流并上传 using (MemoryStream imageStream = new MemoryStream()) { // 将图像保存到内存流,这里选择PNG格式(也可以替换为Jpeg等) cml1.Save(imageStream, ImageFormat.Png); // 重置流的位置到开头——这一步非常重要,否则Azure会读取空内容 imageStream.Position = 0; // 直接从内存流上传到Azure Blob blockBlob.UploadFromStream(imageStream); } // 可选:设置Blob的内容类型,让浏览器可以直接预览图像 blockBlob.Properties.ContentType = "image/png"; blockBlob.SetProperties(); }
关键细节说明
- 内存流的使用:用
MemoryStream在内存中暂存图像数据,完全跳过本地文件的写入和读取操作,既提升效率又避免磁盘IO开销。 - 流位置重置:调用
Image.Save后,流的指针会停在内容末尾,必须通过imageStream.Position = 0将指针移回开头,否则Azure Blob服务读取到的会是空白内容。 - 图像格式选择:你可以根据需求替换
ImageFormat.Png为ImageFormat.Jpeg(注意Jpeg是有损压缩),同时记得同步修改ContentType为image/jpeg。 - Blob命名规则:用高精度时间戳生成唯一文件名,避免同一容器内的文件重名覆盖。
内容的提问来源于stack exchange,提问作者Sohel
相关产品推荐
相关产品推荐

