参考:
http://www.cnblogs.com/zxx193/p/3605238.html?utm_source=tuicool
http://www.cnblogs.com/freeliver54/p/3430956.html
http://www.cnblogs.com/simhare/archive/2007/07/18/821938.html
定义string变量为str,内存流变量为ms,比特数组为bt
1.字符串=>比特数组
(1)byte[] bt=System.Text.Encoding.Default.GetBytes("字符串"); (2)byte[] bt=Convert.FromBase64String("字符串");
补充:
System.Text.Encoding.Unicode.GetBytes(str); System.Text.Encoding.UTF8.GetBytes(str); System.Text.Encoding.GetEncoding("gb2312").GetBytes(str); //指定编码方式
string str = "中国?ss123?"; byte[] bytes = System.Text.Encoding.Default.GetBytes(str); //gb2312编码 汉字占2个字节、英文字母占1个字节 bytes长度为12 string s = System.Text.Encoding.Default.GetString(new byte[] { bytes[0],bytes[1] });//解码后为“中”
byte[] bytes = {97, 98, 99, 100, 101, 102}; string str = System.Text.Encoding.ASCII.GetString(bytes); //结果为:abcdef ASCII码表
2.比特数组=>字符串
(1)string str=System.Text.Encoding.Default.GetString(bt); (2)string str=Convert.ToBase64String(bt);
3.字符串=>流
(1)MemoryStream ms=new MemoryStream(System.Text.Encoding.Default.GetBytes("字符串")); (2)MemoryStream ms=new MemoryStream(Convert.FromBase64String("字符串"));
4.流=>字符串
(1)string str=Convert.ToBase64String(ms.ToArray()); (2)string str=System.Text.Encoding.Default.GetString(ms.ToArray());
5.比特数组=>流
(1)MemoryStream ms=new MemoryStream(bt); (2)MemoryStream ms=new MemoryStream();ms.Read(bt,0,bt.Lenght);
6.流=>比特数组
(1)byte[] bt=ms.ToArray(); (2)MemoryStream ms=new MemoryStream();ms.Write(bt,0,ms.Length);
7、byte[]与base64string的互相转换
在C#中 图片到byte[]再到base64string的转换: Bitmap bmp = new Bitmap(filepath); MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); string pic = Convert.ToBase64String(arr); base64string到byte[]再到图片的转换: byte[] imageBytes = Convert.FromBase64String(pic); //读入MemoryStream对象 MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length); memoryStream.Write(imageBytes, 0, imageBytes.Length); //转成图片 Image image = Image.FromStream(memoryStream); 现在的数据库开发中:图片的存放方式一般有CLOB:存放base64string BLOB:存放byte[] 一般推荐使用byte[]。因为图片可以直接转换为byte[]存放到数据库中 若使用base64string 还需要从byte[]转换成base64string 。更浪费性能。
8、C# byte数组与Image的相互转换