-
C#教程之C#实现Stream与byte[]之间的转换实例教程
本文以实例形式详细介绍了C#实现Stream与byte[]之间的转换的方法,分享给大家供大家参考之用。具体方法如下:
一、二进制转换成图片
1
2
3
4
5
|
MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Image img = Image.FromStream(ms); ms.Close(); this .pictureBox1.Image |
二、C#中byte[]与string的转换代码
1.
1
2
3
|
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding(); byte [] inputBytes =converter.GetBytes(inputString); string inputString = converter.GetString(inputBytes); |
2.
1
2
3
|
string inputString = System.Convert.ToBase64String(inputBytes); byte [] inputBytes = System.Convert.FromBase64String(inputString); FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); |
三、C# Stream 和 byte[] 之间的转换
1.将 Stream 转成 byte[]
1
2
3
4
5
6
7
8
|
public byte [] StreamToBytes(Stream stream) { byte [] bytes = new byte [stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } |
2.将 byte[] 转成 Stream
1
2
3
4
5
|
public Stream BytesToStream( byte [] bytes) { Stream stream = new MemoryStream(bytes); return stream; } |
四、Stream 和 文件之间的转换
将 Stream 写入文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public void StreamToFile(Stream stream, string fileName) { // 把 Stream 转换成 byte[] byte [] bytes = new byte [stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); // 把 byte[] 写入文件 FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } |
五、从文件读取 Stream
1
2
3
4
5
6
7
8
9
10
11
12
|
public Stream FileToStream( string fileName) { // 打开文件 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); // 读取文件的 byte[] byte [] bytes = new byte [fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); // 把 byte[] 转换成 Stream Stream stream = new MemoryStream(bytes); return stream; } |
六、Bitmap 转化为 Byte[]
1
2
3
4
5
|
Bitmap BitReturn = new Bitmap(); byte [] bReturn = null ; MemoryStream ms = new MemoryStream(); BitReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Png); bReturn = ms.GetBuffer(); |
相信本文所述对大家的C#程序设计有一定的借鉴价值。
栏目列表
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
数据库审计与智能监控:从日志分析到异
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比