方式一:
/// <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); }
程序运行效果:
//将image转换成byte[]数据 private byte[] ImageToByte(System.Drawing.Image img) { MemoryStream ms = new MemoryStream(); img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } //将byte[]数据转换成image private Image ByteToImage(byte[] bytes) { MemoryStream ms = new MemoryStream(bytes); Image img= Image.FromStream(ms); return img; }