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

时间:2015-04-13 20:00:35

标签: windows-phone-8.1 azure-storage-blobs

以下代码将从Azure blob存储中复制图像文件,并在本地创建新的图像文件。然后将此本地图像添加到List以进一步数据绑定到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存储中复制图像文件,并在本地创建新的图像文件。然后将此本地图像添加到List以进一步数据绑定到XAML UI。

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

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

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

2 个答案:

答案 0 :(得分:1)

这会有用吗?

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

希望它有所帮助,

德鲁

答案 1 :(得分:0)

我发现这个作品。它可能不完美,但它有效。欢迎提出意见或更正。

    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;