Base64编码和图片的互相转换

Base64编码在Web方面有很多应用,譬如在URL、电子邮件方面。网上有很多相关的资源用于提供Base64编码和其他编码的转换,.Net Framework也提供了现成的功能类(System.Convert)用于将二进制数据转换为Base64字符串。

 原创文章,转帖请注明出处:blog.csdn.net/sjdev
事出有因

 我们已经做了一个编辑器,这个编辑器可以以xml格式存储一些信息。在存储图片信息时我们碰到了一些问题。我们本来在xml信息中存储的是图片的路径,然而一旦客户把这个信息copy到其他电脑上而没有同时copy相关的图片时,就会出现一些问题。

 后来,我们把图片数据转换为Base64编码,替代了原先存储图片路径的方式。
转换流程

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


view plaincopy to clipboardprint?
/// <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;
 }

转载自:http://blog.csdn.net/sjdev/archive/2009/11/01/4752743.aspx

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值