我尝试将一个base64字符串输出到一个图像,然后使用一个实际的解决方法 - 让我们说 - 不是很优雅。
我从服务器接收TCP流并将其编码为UTF-8。数据包含base64 / png字符串。收到后,我将通过删除服务器回复标题和换行来清理收到的邮件。现在我要将字符串转换为字节,以便将其发送到临时的MemoryStream,用于在最后一步生成图像。
它的代码如下所示:
private void button1_Click(object sender, EventArgs e)
{
//Request the image from server
Networker.send("THUMBNAIL RETRIEVE AMB\r\n");
//Receive the reply from server in UTF-8 and store in string
string received = Networker.receive();
//clean the string by removing not needed information
string cleanreceived = received.Replace("201 THUMBNAIL RETRIEVE OK\r\n", "");
cleanreceived = cleanreceived.Replace("\n", "");
cleanreceived = cleanreceived.Replace("\r", "");
//convert string to byte[]
byte[] imageBytes = Convert.FromBase64String(cleanreceived);
// Convert byte[] to image and display in a pictureBox
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
pictureBox1.Image = image;
}
}
然而,这让我失败了,Convert.FromBase64String的输入是无效的Base64字符串序列。我只是想,问题是,我将流编码为UTF-8,但后来我尝试了以下内容:
private void button1_Click(object sender, EventArgs e)
{
//Request the image from server
Networker.send("THUMBNAIL RETRIEVE AMB\r\n");
//Receive the reply from server in UTF-8 and store in string
string received = Networker.receive();
//clean the string by removing not needed information
string cleanreceived = received.Replace("201 THUMBNAIL RETRIEVE OK\r\n", "");
cleanreceived = cleanreceived.Replace("\n", "");
cleanreceived = cleanreceived.Replace("\r", "");
//store the clean text in a richTextBox
richTextBox1.Text = cleanreceived;
//store the text of the richTextBox in a new string
string base64 = richTextBox1.Text;
//convert string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64);
// Convert byte[] to image and display in a pictureBox
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, false);
pictureBox1.Image = image;
}
}
而且..它有效。所以我所做的是将字符串发送到文本框,然后将其调用回新字符串。使用该字符串,我可以从Base64转换为字节,依此类推。
但是,有没有办法让这项工作更轻松,更优雅,而不需要那个文本框?
在此先感谢并亲切问候,托比亚斯