首页 > 代码库 > c# Base64编码和图片的互相转换代码

c# Base64编码和图片的互相转换代码

将图片转化为Base64字符串的流程是:首先使用BinaryFormatter将图片文件序列化为二进制数据,然后使用Convert类的ToBase64String方法。将Base64字符串转换为图片的流程正好相反:使用Convert类的FromBase64String得到图片文件的二进制数据,然后使用BinaryFormatter反序列化方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/// <summary>
    /// 将图片数据转换为Base64字符串
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ToBase64(object sender, EventArgs e)
    {
      Image img = this.pictureBox.Image;
      BinaryFormatter binFormatter = new BinaryFormatter();
      MemoryStream memStream = new MemoryStream();
      binFormatter.Serialize(memStream, img);
      byte[] bytes = memStream.GetBuffer();
      string base64 = Convert.ToBase64String(bytes);
      this.richTextBox.Text = base64;
    }
 
    /// <summary>
    /// 将Base64字符串转换为图片
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ToImage(object sender, EventArgs e)
    {
      string base64 = this.richTextBox.Text;
      byte[] bytes = Convert.FromBase64String(base64);
      MemoryStream memStream = new MemoryStream(bytes);
      BinaryFormatter binFormatter = new BinaryFormatter();
      Image img = (Image)binFormatter.Deserialize(memStream);
      this.pictureBox.Image = img;
    }

c# Base64编码和图片的互相转换代码