public static async Task<StorageFile> CacheManager(string url, Crop crop) { // Initialize cache folder // Get the app's local folder. StorageFolder localFolder = ApplicationData.Current.LocalFolder; // Create a new subfolder in the current folder. StorageFolder cacheFolder = await localFolder.CreateFolderAsync(Constants.CacheFolder, CreationCollisionOption.OpenIfExists); string key = Util.GenerateKey(url); StorageFile file = null; try { file = await cacheFolder.GetFileAsync(key); } catch (FileNotFoundException) { Debug.WriteLine("File " + key + " is not cached"); byte[] bytes = await Net.Download(url); file = await cacheFolder.CreateFileAsync(key, CreationCollisionOption.GenerateUniqueName); if (null != crop) { bytes = await Transform.CropImage(bytes, crop); } await FileIO.WriteBytesAsync(file, bytes); } return file; }
public static async Task<byte[]> CropImage(byte[] stream, Crop crop) { byte[] byteArray = null; var imageStream = new MemoryStream(stream); var fileStream = imageStream.AsRandomAccessStream(); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream(); BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder); BitmapBounds bounds = new BitmapBounds(); bounds.Height = (uint)crop.Height; bounds.Width = (uint)crop.Width; bounds.X = (uint)crop.X; bounds.Y = (uint)crop.Y; enc.BitmapTransform.Bounds = bounds; enc.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear; enc.IsThumbnailGenerated = false; try { await enc.FlushAsync(); } catch (Exception ex) { Debug.WriteLine("Error croping image", ex); } byteArray = new byte[ras.Size]; DataReader dataReader = new DataReader(ras.GetInputStreamAt(0)); await dataReader.LoadAsync((uint)ras.Size); dataReader.ReadBytes(byteArray); return byteArray; }
public static async Task<StorageFile> Load(string url, Crop crop) { return await Loader.CacheManager(url, crop); }