ImageToolsDroid.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.IO;
  5. using Android.Content;
  6. using Android.Graphics;
  7. using Android.Media;
  8. using Java.IO;
  9. using Bitmap = Android.Graphics.Bitmap;
  10. using File = System.IO.File;
  11. using Path = System.IO.Path;
  12. [assembly: Xamarin.Forms.Dependency(typeof(InABox.Mobile.Android.ImageToolsDroid))]
  13. namespace InABox.Mobile.Android
  14. {
  15. public class ImageToolsDroid: IImageTools
  16. {
  17. public byte[] CreateVideoThumbnail(byte[] video, float maxwidth, float maxheight)
  18. {
  19. byte[] result = null;
  20. var filename = Path.Combine(
  21. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  22. $"{Guid.NewGuid().ToString()}.tmp"
  23. );
  24. File.WriteAllBytes(filename,video);
  25. using (FileInputStream fs = new FileInputStream(filename))
  26. {
  27. FileDescriptor fd = fs.FD;
  28. MediaMetadataRetriever retriever = new MediaMetadataRetriever();
  29. retriever.SetDataSource(fd);
  30. Bitmap bitmap = retriever.GetFrameAtTime(0);
  31. if (bitmap != null)
  32. {
  33. MemoryStream stream = new MemoryStream();
  34. bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
  35. result = stream.ToArray();
  36. }
  37. }
  38. File.Delete(filename);
  39. if (result != null)
  40. result = CreateThumbnail(result, maxwidth, maxheight);
  41. return result;
  42. }
  43. public byte[] CreateThumbnail(byte[] source, float maxwidth, float maxheight)
  44. {
  45. byte[] result = { };
  46. using (var image = BitmapFactory.DecodeByteArray(source, 0, source.Length))
  47. {
  48. if (image != null)
  49. {
  50. var size = new Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width);
  51. if ((size.Width > 0) && (size.Height > 0))
  52. {
  53. var maxFactor = Math.Min(maxwidth / size.Width, maxheight / size.Height);
  54. var width = maxFactor * size.Width;
  55. var height = maxFactor * size.Height;
  56. using (var tgt = Bitmap.CreateScaledBitmap(image, (int)height, (int)width, true))
  57. {
  58. if (tgt != null)
  59. {
  60. using (var ms = new MemoryStream())
  61. {
  62. tgt.Compress(Bitmap.CompressFormat.Jpeg, 95, ms);
  63. result = ms.ToArray();
  64. }
  65. tgt.Recycle();
  66. }
  67. }
  68. }
  69. image.Recycle();
  70. }
  71. }
  72. return result;
  73. }
  74. }
  75. }