如何从 azure blob 容器中获取图像列表并将它们更改为 c# 中的缩略图?

How to get list of images from azure blob container and change them into thumbnail in c#?

我正在从 azure blob 中获取图像并将其转换为缩略图。

当我 运行 下面的代码时,我给出容器的路径,如“https://storageaccountname.blob.core.windows.net/images/” 但它显示错误:-
System.IO.FileNotFoundException: C:\Users\Lenovo\Desktop\xxx\sample1.jpg

代码在 foreach 行之前工作正常,因为我正在从我的 azure 中获取文件“sample1.jpg”,但在那之后 Image.FromFile 开始在我的本地桌面中查找文件

public async Task < List < byte[] >> GetImageInThumbnail(string path) {
  List < byte[] > result = new List < byte[] > ();
  var blobServiceClient = new BlobServiceClient("myconnectionstring");
  var container = blobServiceClient.GetBlobContainerClient("images");

  List < string > blobNames = new List < string > ();
  var blobs = container.GetBlobsAsync(BlobTraits.None, BlobStates.None);
  await foreach(var blob in blobs) {
    blobNames.Add(blob.Name);
  }
  foreach(string blobItems in blobNames) {
    var image = Image.FromFile(blobItems.Split('/').Last());
    var resized = new Bitmap(image, new Size(150, 75));
    using MemoryStream imageStream = new MemoryStream();
    resized.Save(imageStream, ImageFormat.Jpeg);
    byte[] imageContent = new byte[imageStream.Length];
    imageStream.Position = 0;
    imageStream.Read(imageContent, 0, (int) imageStream.Length);
    result.Add(imageContent);
  }
  return result;
}

当你打电话时:

var image = Image.FromFile(blobItems.Split('/').Last());

您正在尝试仅通过文件名(.Last())获取图像,Image.FromFile然后尝试在当前工作目录中获取图像。在启动时,这是您启动应用程序的目录,这可能是可执行文件所在的目录(但不能是)。请注意,此工作目录可能会更改!

您需要先下载真实图像(为了简单起见,我忽略了您的调整大小)

foreach(string blobItems in blobNames) 
{      
    using MemoryStream imageStream = new MemoryStream();
    //key part to get the image from the blob
    CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(blobItems.Split('/').Last());
    await cloudBlockBlob.DownloadToStreamAsync(imageStream );
    // now you do wat you want with the data you got ;)
    byte[] imageContent = new byte[imageStream.Length];
   imageStream.Position = 0;
   imageStream.Read(imageContent, 0, (int) imageStream.Length);
   result.Add(imageContent);
}