MobileDocument.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Plugin.Media;
  5. namespace InABox.Mobile
  6. {
  7. public abstract class MobileDocumentSource
  8. {
  9. public abstract Task<MobileDocument> GetDocument();
  10. }
  11. public class MobileDocumentCameraSource : MobileDocumentSource
  12. {
  13. public override async Task<MobileDocument> GetDocument()
  14. {
  15. await CrossMedia.Current.Initialize();
  16. if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
  17. {
  18. throw new Exception("No Camera Available");
  19. }
  20. String filename = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}.png";
  21. var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
  22. {
  23. Name = filename,
  24. CompressionQuality = 5,
  25. PhotoSize = Plugin.Media.Abstractions.PhotoSize.Large
  26. });
  27. if (file == null)
  28. return null;
  29. byte[] data;
  30. await using (var stream = file.GetStream())
  31. {
  32. BinaryReader br = new BinaryReader(stream);
  33. data = br.ReadBytes((int)stream.Length);
  34. }
  35. return new MobileDocument(filename, data);
  36. }
  37. }
  38. public class MobileDocumentLibrarySource : MobileDocumentSource
  39. {
  40. public override async Task<MobileDocument> GetDocument()
  41. {
  42. await CrossMedia.Current.Initialize();
  43. if (!CrossMedia.Current.IsPickPhotoSupported)
  44. throw new Exception("No Photo Library available");
  45. var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions()
  46. {
  47. CompressionQuality = 5,
  48. PhotoSize = Plugin.Media.Abstractions.PhotoSize.Large
  49. });
  50. if (file == null)
  51. return null;
  52. byte[] data;
  53. await using (var stream = file.GetStream())
  54. {
  55. BinaryReader br = new BinaryReader(stream);
  56. data = br.ReadBytes((int)stream.Length);
  57. }
  58. return new MobileDocument(file.OriginalFilename,data);
  59. }
  60. }
  61. public class MobileDocument
  62. {
  63. public string FileName { get; set; }
  64. public byte[] Data { get; set; }
  65. public MobileDocument(string filename, byte[] data)
  66. {
  67. FileName = filename;
  68. Data = data;
  69. }
  70. public static async Task<MobileDocument> From<T>()
  71. where T : MobileDocumentSource, new()
  72. {
  73. return await new T().GetDocument();
  74. }
  75. }
  76. }