using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IStation.Untity { /// /// 流转换 /// public class StreamTransfer { /// /// 转换为字节数组 /// public static byte[] ToBytes(Stream stream) { if (stream == null) return default; try { var positon = stream.Position; var bts = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(bts, 0, bts.Length); stream.Position = positon; return bts; } catch { return default; } } /// /// 从字节数组中转换为流 /// public static Stream FromBytes(byte[] bts) { if (bts == null) return null; var stream = new MemoryStream(bts); stream.Position = 0; return stream; } /// /// 从图片转换为流 /// public static Stream FromImage(Image img) { if (img == null) return default; try { var ms = new MemoryStream(); img.Save(ms, img.RawFormat); ms.Position = 0; return ms; } catch { return default; } } /// /// 从文件转换为流 /// public static Stream FromFile(string fileName) { if (string.IsNullOrEmpty(fileName)) return default; if (!File.Exists(fileName)) return default; try { using (var stream = new FileStream(fileName, FileMode.Open)) { var ms = new MemoryStream(); stream.CopyTo(ms); ms.Position = 0; return ms; } } catch { return default; } } /// /// 转换为文件 /// public static void ToFile(Stream stream, string fileName) { if (stream == null) return; if (string.IsNullOrEmpty(fileName)) return; try { using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { var position = stream.Position; stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); stream.Position = position; } } catch (SystemException ex) { throw ex; } } } }