WPFイメージコントロールSource:Byte[],BitmapImage相互変換
3940 ワード
ファイルをbyte[]に変換
byte[]BitmapImageに変換:
BitmapImageから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;
}
WriteableBitmap wb = new WriteableBitmap(img.Source as BitmapSource);// Image WriteableBitmap
byte[] b = Convert.FromBase64String(GetBase64Image(wb));// byte