在 Windows Phone 8.1 中将 Azure Blob 图像下载到内存流

Download Azure Blob image to memorystream in Windows Phone 8.1

下面的代码将从 Azure blob 存储复制一个图像文件,并在本地创建一个新的图像文件。该本地图像随后将添加到列表中,以进一步绑定到 XAML UI.

        string accountName = "testacc";
        string accountKey = "123abc";
        string container = "textcontainer";

        List<Mydata> items = new List<Mydata>();
        BitmapImage bitmapToShow = new BitmapImage();

        StorageCredentials creds = new StorageCredentials(accountName, accountKey);
        CloudStorageAccount acc = new CloudStorageAccount(creds, useHttps: true);
        CloudBlobClient cli = acc.CreateCloudBlobClient();
        CloudBlobContainer sampleContainer = cli.GetContainerReference(container);
        CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("xbox.jpg");

        // Here I need to copy the data stream directely to the BitmapImage instead of creating a file first
        StorageFile photoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp_image.jpg", CreationCollisionOption.ReplaceExisting);
        await blob.DownloadToFileAsync(photoFile);
        bitmapToShow = new BitmapImage(new Uri(photoFile.Path));

        items.Add(new Mydata() { image = bitmapToShow });

        DataBinding.ItemsSource = items;

下面的代码将从 Azure blob 存储复制一个图像文件,并在本地创建一个新的图像文件。该本地图像随后将添加到列表中,以进一步绑定到 XAML UI.

Hovewer - 为了提高效率,我正在寻找一种方法来避免首先在本地创建图像文件。我正在寻找一种方法,将 Azure blob 存储中的图像文件复制到 MemoryStream,然后直接传递到 BitmapImage。

我还没有想到自己编写代码,而且我没有找到的代码片段不适用于 Windows Phone 8.1。我正在用 C# 为 Windows Phone 8.1 Universal App(不是 Silverlight)编程。

有人可以帮助我获得该功能所需的代码吗?

这行得通吗?

Stream photoStream = await blob.DownloadToStreamAsync(photoFile)
bitmapToShow = new BitmapImage(photoStream);

希望对您有所帮助,

德鲁

我发现这个有效。它可能不完美,但它有效。欢迎评论或指正。

    string accountName = "testacc";
    string accountKey = "123abc";
    string container = "textcontainer";

    List<Mydata> items = new List<Mydata>();
    BitmapImage bitmapToShow = new BitmapImage();
    InMemoryRandomAccessStream memstream = new InMemoryRandomAccessStream();

    StorageCredentials creds = new StorageCredentials(accountName, accountKey);
    CloudStorageAccount acc = new CloudStorageAccount(creds, useHttps: true);
    CloudBlobClient cli = acc.CreateCloudBlobClient();
    CloudBlobContainer sampleContainer = cli.GetContainerReference(container);
    CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("xbox.jpg");

    await blob.DownloadToStreamAsync(memstream.CloneStream());
    bitmapToShow.SetSource(memstream);

    items.Add(new Mydata() { image = bitmapToShow });

    DataBinding.ItemsSource = items;