圖片和字符轉換一版用在socket進行通訊之間。如今我就把我寫的和測試整理出來和你們分享下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表示圖片存在的位置ui
註釋2:tb_position.Text表示字符保存位置this
註釋3:string tempStr = Convert.ToString(tempByte, 16); 字節轉換成16進制字符串spa
2:16進制字符轉換成圖片code
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 表示轉換圖片保存位置blog
註釋2:lbl_text.Text表示要轉換字符的位置圖片
註釋3: byte tempByte = Convert.ToByte(str[i], 16);16進制字符轉成字符ip
運行效果字符串