using System; using System.IO; using System.Threading.Tasks; using Plugin.Media; namespace InABox.Mobile { public abstract class MobileDocumentSource { public abstract Task GetDocument(); } public class MobileDocumentCameraSource : MobileDocumentSource { public override async Task GetDocument() { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { throw new Exception("No Camera Available"); } String filename = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}.png"; var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Name = filename, CompressionQuality = 5, PhotoSize = Plugin.Media.Abstractions.PhotoSize.Large }); if (file == null) return null; byte[] data; await using (var stream = file.GetStream()) { BinaryReader br = new BinaryReader(stream); data = br.ReadBytes((int)stream.Length); } return new MobileDocument(filename, data); } } public class MobileDocumentLibrarySource : MobileDocumentSource { public override async Task GetDocument() { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsPickPhotoSupported) throw new Exception("No Photo Library available"); var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions() { CompressionQuality = 5, PhotoSize = Plugin.Media.Abstractions.PhotoSize.Large }); if (file == null) return null; byte[] data; await using (var stream = file.GetStream()) { BinaryReader br = new BinaryReader(stream); data = br.ReadBytes((int)stream.Length); } return new MobileDocument(file.OriginalFilename,data); } } public class MobileDocument { public string FileName { get; set; } public byte[] Data { get; set; } public MobileDocument(string filename, byte[] data) { FileName = filename; Data = data; } public static async Task From() where T : MobileDocumentSource, new() { return await new T().GetDocument(); } } }