Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. [assembly: Xamarin.Forms.Dependency(typeof(ImageHelpers))]
  2. namespace MultiImagePicker.Droid.Helpers
  3. {
  4. public class ImageHelpers : ICompressImages
  5. {
  6. //collectionName is the name of the folder in your Android Pictures directory.
  7. public static readonly string collectionName = "TmpPictures";
  8.  
  9. public string SaveFile(byte[] imageByte, string fileName)
  10. {
  11. var fileDir = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures), collectionName);
  12. if (!fileDir.Exists())
  13. {
  14. fileDir.Mkdirs();
  15. }
  16.  
  17. var file = new Java.IO.File(fileDir, fileName);
  18. System.IO.File.WriteAllBytes(file.Path, imageByte);
  19.  
  20. return file.Path;
  21. }
  22.  
  23. public string CompressImage(string path)
  24. {
  25. byte[] imageBytes;
  26.  
  27. //Get the bitmap.
  28. var originalImage = BitmapFactory.DecodeFile(path);
  29.  
  30. //Set imageSize and imageCompression parameters.
  31. var imageSize = .86;
  32. var imageCompression = 67;
  33.  
  34. //Resize it and then compress it to Jpeg.
  35. var width = (originalImage.Width * imageSize);
  36. var height = (originalImage.Height * imageSize);
  37. var scaledImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, true);
  38.  
  39. using (MemoryStream ms = new MemoryStream())
  40. {
  41. scaledImage.Compress(Bitmap.CompressFormat.Jpeg, imageCompression, ms);
  42. imageBytes = ms.ToArray();
  43. }
  44.  
  45. originalImage.Recycle();
  46. originalImage.Dispose();
  47. GC.Collect();
  48.  
  49. return SaveFile(imageBytes, Guid.NewGuid().ToString());
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement