檔案位元組相互轉換(word、圖片、pdf...)
阿新 • • 發佈:2018-12-18
方式一:
/// <summary> /// word檔案轉換二進位制資料(用於儲存資料庫) /// </summary> /// <param name="wordPath">word檔案路徑</param> /// <returns>二進位制</returns> public byte[] WordConvertByte(string wordPath) { if (!File.Exists(wordPath)) { return null; } byte[] bytContent = null; System.IO.FileStream fs = null; System.IO.BinaryReader br = null; try { fs = new FileStream(wordPath, System.IO.FileMode.Open); br = new BinaryReader((Stream)fs); bytContent = br.ReadBytes((Int32)fs.Length); fs.Close(); br.Close(); } catch { fs.Close(); br.Close(); return null; } return bytContent; } /// <summary> ///二進位制資料轉換為word檔案 /// </summary> /// <param name="data">二進位制資料</param> /// <param name="fileName">word檔名</param> /// <returns>word儲存的相對路徑</returns> public string ByteConvertWord(byte[] data, string fileName) { if (data == null) return string.Empty; FileStream fs = null; BinaryWriter br = null; try { fs = new FileStream(fileName, FileMode.OpenOrCreate); br = new BinaryWriter(fs); br.Write(data, 0, data.Length); br.Close(); fs.Close(); } catch { br.Close(); fs.Close(); return string.Empty; } return fileName; }
方式二:
// <summary> /// 根據圖片路徑返回圖片的位元組流byte[] /// </summary> /// <param name="imagePath">圖片路徑</param> /// <returns>返回的位元組流</returns> private byte[] ImageToByte(string imagePath) { FileStream files = new FileStream(imagePath, FileMode.Open); byte[] imgByte = new byte[files.Length]; files.Read(imgByte, 0, imgByte.Length); files.Close(); return imgByte; } /// <summary> /// 位元組陣列生成圖片 /// </summary> /// <param name="Bytes">位元組陣列</param> /// <returns>圖片</returns> private Image ByteArrayToImage(byte[] Bytes) { MemoryStream ms = new MemoryStream(Bytes); return Bitmap.FromStream(ms, true); }
程式執行效果: