将图像列表下载到位图数组C#

时间:2013-01-11 16:07:43

标签: c# image xaml windows-8

我的应用中有一个组件需要预先加载某些图像。我的想法是,我应该将所有图像从网上下载到Bitmap对象中,然后将它们用作我的图像中的源。最简单的方法是什么?我已经编写了一些代码来下载图像,但它似乎不适用于多个图像:

 HttpClient client = new HttpClient();
        NetResult result;

        try
        {

            Debug.WriteLine("Starting call to " + Url);
            HttpResponseMessage response = await client.GetAsync(Url);
            response.EnsureSuccessStatusCode();
            result = await this.processContent(response.Content);

        }
        catch (Exception e) 
        {

            Debug.WriteLine(e.Message);
            Debug.WriteLine("Unable to load " + Url);
            result = new NetResult(NetResultStatus.Failure, "Could not connect to " + Url + ".");

}

...

和ProcessContent的工作原理如下:

public override async Task<NetResult> processContent(HttpContent content)
    {

        InMemoryRandomAccessStream randomAccessStream = null;

        if (content != null && !Constants.FakeInternet)
        {
            byte[] img = await content.ReadAsByteArrayAsync();
            // Transform to a stream
            randomAccessStream = new InMemoryRandomAccessStream();
            DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
            writer.WriteBytes(img);
            await writer.StoreAsync();
        }

        _m = new ManualResetEvent(false);

        (Application.Current as App).UIDispatcher.DispatchAsync(() =>
            {


                    // Create bitmap image
                    image = new BitmapImage();

                    NetImage i = (NetImage)this;

                    Debug.WriteLine("Creating Image " + Url);
                    image.ImageFailed += ImageFailed;
                    image.ImageOpened += ImageOpened;
                    image.SetSource(randomAccessStream);


            });

        _m.WaitOne();


        return await base.processContent(content);

    }

    void ImageOpened(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {

        Debug.WriteLine("Image opened: " + Url);
        _m.Set();

    }

    void ImageFailed(object sender, Windows.UI.Xaml.ExceptionRoutedEventArgs e)
    {

        Debug.WriteLine("Image failed: " + Url);
        image = null;
        ConnectionState = ConnectionState.Failed;
        _m.Set();

    }

我是否可以使用内置API将PNG从网上下载到Bitmap对象中?我想其中一个令人讨厌的事情是我必须解码UI线程上的Bitmap ......为什么会这样?

1 个答案:

答案 0 :(得分:0)

我不知道WinRT API会为您节省下载PNG和创建BitmapImage的一些步骤。这并不意味着一个人不存在。

您可能会发现在XAML Images Sample中查看方案4会很有帮助。它异步计算后台线程上的分形,然后在WriteableBitmap中显示结果。这将使您脱离UI线程。