当前位置: 代码迷 >> .NET相关 >> 16进制字符和图片其间相互转换
  详细解决方案

16进制字符和图片其间相互转换

热度:219   发布时间:2016-04-24 02:47:50.0
16进制字符和图片之间相互转换

  图片和字符转换一版用在socket进行通信之间。现在我就把我写的和测试整理出来和大家分享下

1:图片转换成16进制字符

 1   FileStream fs = new FileStream(lbl_show.Text, FileMode.Open, FileAccess.Read); 2             BinaryReader br = new BinaryReader(fs); 3             StreamWriter sw = new StreamWriter(tb_position.Text); 4             int length = (int)fs.Length; 5             StringBuilder sb = new StringBuilder(); 6             while (length > 0) 7             { 8                 byte tempByte = br.ReadByte(); 9                 string tempStr = Convert.ToString(tempByte, 16);10                 if (tempStr.Length <= 1)11                 {12                     tempStr = "0" + tempStr;13                 }14                 sb.Append(tempStr);15                 length--;16             }17             sw.Write(sb.ToString());18             fs.Close();19             br.Close();20             sw.Close();21             MessageBox.Show("转换成功"); 

注释1:lbl_show.Text表示图片存在的位置

注释2:tb_position.Text表示字符保存位置

注释3:string tempStr = Convert.ToString(tempByte, 16); 字节转换成16进制字符串

2:16进制字符转换成图片

 1     FileStream fs = new FileStream("Imgs//test.jpg", FileMode.Create, FileAccess.Write); 2             BinaryWriter bw = new BinaryWriter(fs); 3             StreamReader sr = new StreamReader(lbl_text.Text); 4             while (sr.Peek() != -1) 5             { 6                 string tempStr = sr.ReadToEnd(); 7                 if (tempStr.Contains("7D01") || tempStr.Contains("7D02")) 8                 { 9                     tempStr = tempStr.Replace("7D02", "7E");10                     tempStr = tempStr.Replace("7D01", "7D");11                 }12                 int tlenth = tempStr.Length / 2;13                 int pos = 0;14                 string[] str = new string[tlenth];15                 for (int i = 0; i < tlenth; i++)16                 {17                     str[i] = tempStr.Substring(pos, 2);18                     pos = pos + 2;19                     string cc = str[i];20                     byte tempByte = Convert.ToByte(str[i], 16);21                     bw.Write(tempByte);22                 }23             }24             fs.Close();25             bw.Close();26             sr.Close();27             this.pictureBox1.Image = Image.FromFile("Imgs//test.jpg");

注释1:Imgs//test.jpg 表示转换图片保存位置

注释2:lbl_text.Text表示要转换字符的位置

注释3: byte tempByte = Convert.ToByte(str[i], 16);16进制字符转成字符

运行效果

源码下载

  相关解决方案