0
我的應用程序中有一個組件需要預加載某些圖像。我的想法是,我應該將所有來自Web的圖像加載到Bitmap對象中,然後將這些圖像用作我的圖像中的源代碼。什麼是最簡單的方法來做到這一點?我已經寫了一些代碼已經下載圖像,但它似乎並不多張圖片的工作:將圖像列表下載到位圖數組C#
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線程上解碼位圖...爲什麼是這樣?
謝謝,這是至少半幫助:)不必在UI線程上簡化一些與調度程序和手動resetevent的東西,這可能會搞砸當我試圖同時下載多個圖像。 –