ImageToolsDroid.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Drawing;
  3. using System.IO;
  4. using Android.Graphics;
  5. using Bitmap = Android.Graphics.Bitmap;
  6. [assembly: Xamarin.Forms.Dependency(typeof(InABox.Mobile.Android.ImageToolsDroid))]
  7. namespace InABox.Mobile.Android
  8. {
  9. public class ImageToolsDroid: IImageTools
  10. {
  11. public byte[] CreateThumbnail(byte[] source, float maxwidth, float maxheight)
  12. {
  13. byte[] result = { };
  14. using (var image = BitmapFactory.DecodeByteArray(source, 0, source.Length))
  15. {
  16. if (image != null)
  17. {
  18. var size = new Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width);
  19. if ((size.Width > 0) && (size.Height > 0))
  20. {
  21. var maxFactor = Math.Min(maxwidth / size.Width, maxheight / size.Height);
  22. var width = maxFactor * size.Width;
  23. var height = maxFactor * size.Height;
  24. using (var tgt = Bitmap.CreateScaledBitmap(image, (int)height, (int)width, true))
  25. {
  26. if (tgt != null)
  27. {
  28. using (var ms = new MemoryStream())
  29. {
  30. tgt.Compress(Bitmap.CompressFormat.Jpeg, 95, ms);
  31. result = ms.ToArray();
  32. }
  33. tgt.Recycle();
  34. }
  35. }
  36. }
  37. image.Recycle();
  38. }
  39. }
  40. return result;
  41. }
  42. }
  43. }