public async static void LoadImageFromUrl (ImageView iv, string url, BitmapFactory.Options options = null, int scaleWidth = -1, int scaleHeight = -1, BitmapCompressOptions compressOptions = null) { await _loadQueueSemaphore.WaitAsync (); if (_loadedImageViews.Contains (iv)) _loadedImageViews.Remove (iv); var l = new CachedImageLoader (url); var bitmap = await l.LoadInternal (options, scaleWidth, scaleHeight, compressOptions); _loadQueueSemaphore.Release (); if (bitmap != null && !_loadedImageViews.Contains (iv)) { iv.SetImageBitmap (bitmap); _loadedImageViews.Add (iv); } }
public async Task<Bitmap> LoadInternal (BitmapFactory.Options o = null, int scaleWidth = -1, int scaleHeight = -1, BitmapCompressOptions compressOptions = null) { if (String.IsNullOrEmpty (_url)) { return null; } Bitmap bmp = null; if (compressOptions == null) { compressOptions = new BitmapCompressOptions (); } try { var uri = new Uri (_url); var client = new WebClient (); var stringme = String.Format ("{0}{1}{2}", _url, scaleWidth, scaleHeight); var urlHash = GetMD5 (new Java.Lang.String (stringme)); var path = Application.Context.CacheDir.AbsolutePath + "/" + urlHash; var fileInfo = new FileInfo (path); if (o == null) { o = new BitmapFactory.Options () { InPurgeable = true }; } if (_staticRAMCache.ContainsKey (urlHash)) { return _staticRAMCache [urlHash]; } if (fileInfo.Exists) { using (var file = File.Open (path, FileMode.Open, FileAccess.Read)) { byte[] buff = new byte[file.Length]; await file.ReadAsync (buff, 0, (int)file.Length); bmp = await BitmapFactory.DecodeByteArrayAsync (buff, 0, buff.Length, o); _staticRAMCache [urlHash] = bmp; return bmp; } } else { try { Log.Debug ("Loading " + uri.ToString ()); var response = await client.DownloadDataTaskAsync (uri); if (response == null || response.Length <= 0) return null; if (scaleWidth > 0 && scaleHeight > 0) { o.InSampleSize = CalculateInSampleSize (o, scaleWidth, scaleHeight); } bmp = await BitmapFactory.DecodeByteArrayAsync (response, 0, response.Length, o); if (fileInfo.Directory != null) { fileInfo.Directory.Create (); } var fileStream = new FileStream (path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); await bmp.CompressAsync (compressOptions.Format, compressOptions.Quality, fileStream); fileStream.Close (); _staticRAMCache [urlHash] = bmp; return bmp; } catch (WebException ex) { Log.Debug (TAG, ex.StackTrace); return null; } } } catch (System.UriFormatException ex) { Log.Debug (TAG, ex.StackTrace); return null; } }