您的位置:首页 > 其它

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

2015-07-20 10:43 309 查看
图片和字符转换一版用在socket进行通信之间。现在我就把我写的和测试整理出来和大家分享下

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

FileStream fs = new FileStream(lbl_show.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
StreamWriter sw = new StreamWriter(tb_position.Text);
int length = (int)fs.Length;
StringBuilder sb = new StringBuilder();
while (length > 0)
{
byte tempByte = br.ReadByte();
string tempStr = Convert.ToString(tempByte, 16);
if (tempStr.Length <= 1)
{
tempStr = "0" + tempStr;
}
sb.Append(tempStr);
length--;
}
sw.Write(sb.ToString());
fs.Close();
br.Close();
sw.Close();
MessageBox.Show("转换成功");


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

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

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

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

FileStream fs = new FileStream("Imgs//test.jpg", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
StreamReader sr = new StreamReader(lbl_text.Text);
while (sr.Peek() != -1)
{
string tempStr = sr.ReadToEnd();
if (tempStr.Contains("7D01") || tempStr.Contains("7D02"))
{
tempStr = tempStr.Replace("7D02", "7E");
tempStr = tempStr.Replace("7D01", "7D");
}
int tlenth = tempStr.Length / 2;
int pos = 0;
string[] str = new string[tlenth];
for (int i = 0; i < tlenth; i++)
{
str[i] = tempStr.Substring(pos, 2);
pos = pos + 2;
string cc = str[i];
byte tempByte = Convert.ToByte(str[i], 16);
bw.Write(tempByte);
}
}
fs.Close();
bw.Close();
sr.Close();
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进制字符转成字符

运行效果



源码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: