public static BitmapImageLoadingInfo CreateDefault() { BitmapImageLoadingInfo result = new BitmapImageLoadingInfo(); result.Image = new BitmapImage(); result.Loaded = false; result.Loading = false; return result; }
public static BitmapImageLoadingInfo CreateDefault() { BitmapImageLoadingInfo result = new BitmapImageLoadingInfo(); result.Image = new BitmapImage(); result.Loaded = false; result.Loading = false; return(result); }
public async void LoadImage() { string file = ImageFileName; if (string.IsNullOrWhiteSpace(file)) { return; } string imagePath = $"{Global.AppDataPath}{Path.DirectorySeparatorChar}{Global.ImagesCacheDirectory}{Path.DirectorySeparatorChar}{file}"; if (!Global.CachedImages.ContainsKey(file)) { Global.CachedImages.Add(file, BitmapImageLoadingInfo.CreateDefault()); } BitmapImageLoadingInfo info = Global.CachedImages[file]; if (info.Loaded) { this.Image = info.Image; } if (info.Loading) { await Task.Run(async() => { // ugly hack to test wheter image is loaded, // assigment of Image.Source before BitmapImage has been loaded causes NullReferenceException in BitmapImage.EndInit() while (info.Loading) { await Task.Delay(100); } }); this.Image = info.Image; } if (info.Loaded || info.Loading) { return; } info.Loading = true; if (File.Exists(imagePath)) { byte[] imageData = File.ReadAllBytes(imagePath); MemoryStream stream = new MemoryStream(imageData); info.Image.BeginInit(); info.Image.CacheOption = BitmapCacheOption.OnLoad; info.Image.StreamSource = stream; info.Image.EndInit(); this.Image = info.Image; info.Loaded = true; } else { MemoryStream memory = new MemoryStream(); bool success = await Task.Run <bool>(() => { Stream stream = null; if (IsContextValid && !m_context.OnlyContext) { stream = m_context.GetManufacturerImageStream(); } else if (!Custom && !string.IsNullOrWhiteSpace(ManufacturerImageLink)) { try { HttpWebRequest request = Requests.CreateDefaultRequest(ManufacturerImageLink); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); stream = response.GetResponseStream(); } catch { stream = null; } } if (stream != null) { FileStream fileStream = new FileStream(imagePath, FileMode.Create); try { byte[] buffer = new byte[1024]; int len; while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) { memory.Write(buffer, 0, len); fileStream.Write(buffer, 0, len); } } finally { stream.Close(); fileStream.Close(); } return(true); } return(false); }); if (success) { memory.Seek(0, SeekOrigin.Begin); info.Image.BeginInit(); info.Image.CacheOption = BitmapCacheOption.OnLoad; info.Image.StreamSource = memory; info.Image.EndInit(); this.Image = info.Image; info.Loaded = true; } } info.Loading = false; }