c# Bitmap byte[] Stream 文件相互转换

时间:2021-02-19 17:00:39
  1. //byte[] 转图片
  2. publicstatic Bitmap BytesToBitmap(byte[] Bytes)
  3. {
  4. MemoryStream stream = null;
  5. try
  6. {
  7. stream = new MemoryStream(Bytes);
  8. returnnew Bitmap((Image)new Bitmap(stream));
  9. }
  10. catch (ArgumentNullException ex)
  11. {
  12. throw ex;
  13. }
  14. catch (ArgumentException ex)
  15. {
  16. throw ex;
  17. }
  18. finally
  19. {
  20. stream.Close();
  21. }
  22. }
  23. //图片转byte[]
  24. publicstaticbyte[] BitmapToBytes(Bitmap Bitmap)
  25. {
  26. MemoryStream ms = null;
  27. try
  28. {
  29. ms = new MemoryStream();
  30. Bitmap.Save(ms, Bitmap.RawFormat);
  31. byte[] byteImage = new Byte[ms.Length];
  32. byteImage = ms.ToArray();
  33. return byteImage;
  34. }
  35. catch (ArgumentNullException ex)
  36. {
  37. throw ex;
  38. }
  39. finally
  40. {
  41. ms.Close();
  42. }
  43. }
  44. }
  45. =====================
  46. * Stream 和 byte[] 之间的转换
  47. * - - - - - - - - - - - - - - - - - - - - - - - */
  48. /// <summary>
  49. /// 将 Stream 转成 byte[]
  50. /// </summary>
  51. publicbyte[] StreamToBytes(Stream stream)
  52. {
  53. byte[] bytes = newbyte[stream.Length];
  54. stream.Read(bytes, 0, bytes.Length);
  55. // 设置当前流的位置为流的开始
  56. stream.Seek(0, SeekOrigin.Begin);
  57. return bytes;
  58. }
  59. /// <summary>
  60. /// 将 byte[] 转成 Stream
  61. /// </summary>
  62. public Stream BytesToStream(byte[] bytes)
  63. {
  64. Stream stream = new MemoryStream(bytes);
  65. return stream;
  66. }
  67. /* - - - - - - - - - - - - - - - - - - - - - - - -
  68. * Stream 和 文件之间的转换
  69. * - - - - - - - - - - - - - - - - - - - - - - - */
  70. /// <summary>
  71. /// 将 Stream 写入文件
  72. /// </summary>
  73. publicvoid StreamToFile(Stream stream,string fileName)
  74. {
  75. // 把 Stream 转换成 byte[]
  76. byte[] bytes = newbyte[stream.Length];
  77. stream.Read(bytes, 0, bytes.Length);
  78. // 设置当前流的位置为流的开始
  79. stream.Seek(0, SeekOrigin.Begin);
  80. // 把 byte[] 写入文件
  81. FileStream fs = new FileStream(fileName, FileMode.Create);
  82. BinaryWriter bw = new BinaryWriter(fs);
  83. bw.Write(bytes);
  84. bw.Close();
  85. fs.Close();
  86. }
  87. /// <summary>
  88. /// 从文件读取 Stream
  89. /// </summary>
  90. public Stream FileToStream(string fileName)
  91. {
  92. // 打开文件
  93. FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
  94. // 读取文件的 byte[]
  95. byte[] bytes = newbyte[fileStream.Length];
  96. fileStream.Read(bytes, 0, bytes.Length);
  97. fileStream.Close();
  98. // 把 byte[] 转换成 Stream
  99. Stream stream = new MemoryStream(bytes);
  100. return stream;
  101. }