ImageToolsiOS.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.IO;
  3. using AVFoundation;
  4. using CoreGraphics;
  5. using CoreMedia;
  6. using Foundation;
  7. using UIKit;
  8. [assembly: Xamarin.Forms.Dependency(typeof(InABox.Mobile.iOS.ImageToolsiOS))]
  9. namespace InABox.Mobile.iOS
  10. {
  11. public class ImageToolsiOS : IImageTools
  12. {
  13. public byte[] CreateVideoThumbnail(byte[] video, float maxwidth, float maxheight)
  14. {
  15. byte[] result = null;
  16. var filename = Path.Combine(
  17. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  18. $"{Guid.NewGuid().ToString()}.tmp"
  19. );
  20. File.WriteAllBytes(filename,video);
  21. // perhaps? on IOS, try to use - NSUrl.FromFilename (path) instead of - new Foundation.NSUrl(url)
  22. var asset = AVAsset.FromUrl(NSUrl.FromFilename(filename));
  23. AVAssetImageGenerator imageGenerator = new AVAssetImageGenerator(asset);
  24. //AVAssetImageGenerator imageGenerator = new AVAssetImageGenerator(AVAsset.FromUrl((new Foundation.NSUrl(filename))));
  25. imageGenerator.AppliesPreferredTrackTransform = true;
  26. CMTime actualTime;
  27. NSError error;
  28. CGImage cgImage = imageGenerator.CopyCGImageAtTime(new CMTime(1, 1), out actualTime, out error);
  29. using (var ms = new MemoryStream())
  30. {
  31. var png = new UIImage(cgImage).AsPNG().AsStream();
  32. png.CopyTo(ms);
  33. result = ms.ToArray();
  34. }
  35. if (result != null)
  36. result = CreateThumbnail(result, maxwidth, maxheight);
  37. File.Delete(filename);
  38. return result;
  39. }
  40. public byte[] CreateThumbnail(byte[] source, float maxwidth, float maxheight)
  41. {
  42. byte[] result = { };
  43. using (UIImage src = UIImage.LoadFromData(NSData.FromArray(source)))
  44. {
  45. if (src != null)
  46. {
  47. if ((src.Size.Width > 0.0F) && (src.Size.Height > 0.0F))
  48. {
  49. var maxFactor = Math.Min(maxwidth / src.Size.Width, maxheight / src.Size.Height);
  50. var width = maxFactor * src.Size.Width;
  51. var height = maxFactor * src.Size.Height;
  52. UIGraphics.BeginImageContextWithOptions(new CGSize((float)width, (float)height), true, 1.0f);
  53. src.Draw(new CGRect(0, 0, (float)width, (float)height));
  54. var tgt = UIGraphics.GetImageFromCurrentImageContext();
  55. UIGraphics.EndImageContext();
  56. using (NSData imageData = tgt.AsJPEG())
  57. {
  58. result = new byte[imageData.Length];
  59. System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, result, 0,
  60. Convert.ToInt32(imageData.Length));
  61. }
  62. }
  63. }
  64. }
  65. return result;
  66. }
  67. }
  68. }