专业的编程技术博客社区

网站首页 > 博客文章 正文

(C#编程自学)byte[]和BitMapImage之间的转

baijin 2024-08-15 17:08:55 博客文章 11 ℃ 0 评论

byte[]和BitMapImage之间的转换。这几天一直在搞摄像头周边项目。需要实现对摄像头进行抓拍,在wpf中Image标签的Source属性类型为BitMapImage。而其BitMapImage到数组之间的转换一直是困扰我的问题。进行查找资料总结了一下两个方法。实现BitMapImage到byte[]之间的转换操作,在此分享,互相交流学习。

/// <summary>

/// byte[]转为BitmapImage

/// </summary>

/// <param name="byteArray"></param>

/// <returns></returns>

public static BitmapImage ToImage(byte[] byteArray)

{

BitmapImage bmp = null;

try

{

bmp = new BitmapImage();

bmp.BeginInit();

bmp.StreamSource = new MemoryStream(byteArray);

bmp.EndInit();

}

catch

{

bmp = null;

}

return bmp;

}

/// <summary>

/// BitmapImage转为byte[]

/// </summary>

/// <param name="bmp"></param>

/// <returns></returns>

public static byte[] ToByteArray(BitmapImage bmp)

{

byte[] ByteArray = null;

try

{

Stream stream = bmp.StreamSource;

if (stream != null && stream.Length > 0)

{

stream.Position = 0;

using (BinaryReader br = new BinaryReader(stream))

{

ByteArray = br.ReadBytes((int)stream.Length);

}

}

}

catch

{

return null;

}

return ByteArray;

}

转载请注明出处: C#编程自学_做最好的.net自学资料站_4k8k.net

欢迎访问:http://www.4k8k.net/

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表