16进制字符和图片之间相互转换
生活随笔
收集整理的這篇文章主要介紹了
16进制字符和图片之间相互转换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
圖片和字符轉(zhuǎn)換一版用在socket進行通信之間?,F(xiàn)在我就把我寫的和測試整理出來和大家分享下
1:圖片轉(zhuǎn)換成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("轉(zhuǎn)換成功");
注釋1:lbl_show.Text表示圖片存在的位置
注釋2:tb_position.Text表示字符保存位置
注釋3:string tempStr = Convert.ToString(tempByte, 16); 字節(jié)轉(zhuǎn)換成16進制字符串
2:16進制字符轉(zhuǎn)換成圖片
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 表示轉(zhuǎn)換圖片保存位置
注釋2:lbl_text.Text表示要轉(zhuǎn)換字符的位置
注釋3:byte tempByte = Convert.ToByte(str[i], 16);16進制字符轉(zhuǎn)成字符
運行效果
源碼下載
總結(jié)
以上是生活随笔為你收集整理的16进制字符和图片之间相互转换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redis failover过程
- 下一篇: JAVA8永久代