zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    web_arcgis 步骤
    《程序员修炼之道》读后感
    《人月神话》读后感
    七天开发记录(6)
    七天开发记录(5)
    七天开发记录(4)
    七天开发记录(3)
    七天开发记录(2)
    七天开发记录(1)
    《梦断代码》读后感
  • 原文地址:https://www.cnblogs.com/zhangxiaolei521/p/5986965.html
Copyright © 2011-2022 走看看