private static bool GetCachedImage(string cacheKey, out ImageSource image) { image = null; var buffer = Cache.Get(cacheKey) as byte[]; if (buffer != null) { try { using (var memoryStream = new MemoryStream(buffer)) { image = BitmapSourceHelper.FromStream(memoryStream); } DateTime expiration = DateTime.MinValue; if (buffer.Length >= 16 && Encoding.ASCII.GetString(buffer, buffer.Length - 16, 8) == "EXPIRES:") { expiration = new DateTime(BitConverter.ToInt64(buffer, buffer.Length - 8), DateTimeKind.Utc); } return(expiration > DateTime.UtcNow); } catch (Exception ex) { Debug.WriteLine("{0}: {1}", cacheKey, ex.Message); } } return(false); }
private static ImageSource DownloadImage(Uri uri, string cacheKey) { ImageSource image = null; try { var request = WebRequest.CreateHttp(uri); if (HttpUserAgent != null) { request.UserAgent = HttpUserAgent; } using (var response = (HttpWebResponse)request.GetResponse()) { if (response.Headers["X-VE-Tile-Info"] != "no-tile") // set by Bing Maps { using (var responseStream = response.GetResponseStream()) using (var memoryStream = new MemoryStream()) { responseStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); image = BitmapSourceHelper.FromStream(memoryStream); if (cacheKey != null) { SetCachedImage(cacheKey, memoryStream, GetExpiration(response.Headers)); } } } } } catch (WebException ex) { Debug.WriteLine("{0}: {1}: {2}", uri, ex.Status, ex.Message); } catch (Exception ex) { Debug.WriteLine("{0}: {1}", uri, ex.Message); } return(image); }
private static ImageSource LoadImage(string path) { ImageSource image = null; if (File.Exists(path)) { try { using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { image = BitmapSourceHelper.FromStream(fileStream); } } catch (Exception ex) { Debug.WriteLine("{0}: {1}", path, ex.Message); } } return(image); }