BitmapHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Drawing;
  2. using System.Drawing.Imaging;
  3. using System.IO;
  4. using System.Windows.Media.Imaging;
  5. namespace vCloudUploaderDemo
  6. {
  7. internal class BitmapHelper
  8. {
  9. public static Bitmap BytesToBitmap(byte[] bytes)
  10. {
  11. if (bytes == null)
  12. {
  13. return null;
  14. }
  15. var memory = new MemoryStream(bytes);
  16. var bitmap = (Bitmap)Bitmap.FromStream(memory);
  17. return bitmap;
  18. }
  19. public static byte[] BitmapToBytes(Bitmap bitmap)
  20. {
  21. if (bitmap == null)
  22. {
  23. return null;
  24. }
  25. using (var stream = new MemoryStream())
  26. {
  27. bitmap.Save(stream, ImageFormat.Bmp);
  28. var buffer = new byte[stream.Length];
  29. stream.Position = 0;
  30. stream.Read(buffer, 0, buffer.Length);
  31. return buffer;
  32. }
  33. }
  34. public static BitmapImage BytesToBitmapImage(byte[] bytes)
  35. {
  36. var bitmapImage = new BitmapImage();
  37. bitmapImage.BeginInit();
  38. bitmapImage.StreamSource = new MemoryStream(bytes);
  39. bitmapImage.EndInit();
  40. return bitmapImage;
  41. }
  42. public static BitmapImage BitmapToBitmapImage(Bitmap bitmap)
  43. {
  44. BitmapImage bmpimg = new BitmapImage();
  45. using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  46. {
  47. bitmap.Save(ms, ImageFormat.Png);
  48. bmpimg.BeginInit();
  49. bmpimg.StreamSource = ms;
  50. bmpimg.CacheOption = BitmapCacheOption.OnLoad;
  51. bmpimg.EndInit();
  52. bmpimg.Freeze();
  53. ms.Dispose();
  54. }
  55. return bmpimg;
  56. }
  57. }
  58. }