文件轉為byte[]
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); byte[] desBytes = new byte[fs.Length]; fs.Read(desBytes, 0, desBytes.Length); fs.Close();
byte[]轉換為BitmapImage:
public static BitmapImage ByteArrayToBitmapImage(byte[] byteArray) { BitmapImage bmp = null; try { bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = new MemoryStream(byteArray); bmp.EndInit(); } catch { bmp = null; } return bmp; }
BitmapImage轉換為byte[]:
public static byte[] BitmapImageToByteArray(BitmapImage bmp) { byte[] byteArray = null; try { Stream sMarket = bmp.StreamSource; if (sMarket != null && sMarket.Length > 0) { //很重要,因為Position經常位於Stream的末尾,導致下面讀取到的長度為0。 sMarket.Position = 0; using (BinaryReader br = new BinaryReader(sMarket)) { byteArray = br.ReadBytes((int)sMarket.Length); } } } catch { //other exception handling } return byteArray; }