图片和字符转换一版用在socket进行通信之间。现在我就把我写的和测试整理出来和大家分享下
1:图片转换成16进制字符
1FileStream fs =newFileStream(lbl_show.Text, FileMode.Open, Fileaccess.Read);2BinaryReader br =newBinaryReader(fs);3StreamWriter sw =newStreamWriter(tb_position.Text);4intlength = (int)fs.Length;5StringBuilder sb =newStringBuilder();6while(length >0)7{8bytetempByte =
br.ReadByte();9stringtempStr = Convert.ToString(tempByte,16);10if(tempStr.Length <=1)11{12tempStr ="0"+tempStr;13}14sb.Append(tempStr);15length--;16}17sw.Write(sb.ToString());18fs.Close();19
br.Close();20sw.Close();21MessageBox.Show("转换成功");
注释1:lbl_show.Text表示图片存在的位置
注释2:tb_position.Text表示字符保存位置
注释3:string tempStr = Convert.ToString(tempByte, 16); 字节转换成16进制字符串
2:16进制字符转换成图片
1FileStream fs =newFileStream("Imgs//test.jpg", FileMode.Create, FileAccess.Write);2BinaryWriter bw =newBinaryWriter(fs);3StreamReader sr =newStreamReader(lbl_text.Text);4while(sr.Peek() != -1)5{6stringtempStr =sr.ReadToEnd();7if(tempStr.Contains("7D01") || tempStr.Contains("7D02"))8{9tempStr = tempStr.Replace("7D02","7E");10tempStr = tempStr.Replace("7D01","7D");11}12inttlenth = tempStr.Length /2;13intpos =0;14string[] str =newstring[tlenth];15for(inti =0; i < tlenth; i++)16{17str[i] = tempStr.Substring(pos,2);18pos = pos +2;19stringcc =str[i];20bytetempByte = Convert.ToByte(str[i],16);21bw.Write(tempByte);22}23}24fs.Close();25bw.Close();26sr.Close();27this.pictureBox1.Image = Image.FromFile("Imgs//test.jpg");
注释1:Imgs//test.jpg 表示转换图片保存位置
注释2:lbl_text.Text表示要转换字符的位置
注释3: byte tempByte = Convert.ToByte(str[i], 16);16进制字符转成字符
运行效果
源码下载