C#实现字符串与图片的Base64编码转换操作示例
本文实例讲述了C#实现字符串与图片的Base64编码转换操作。分享给大家供大家参考,具体如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO;
usingSystem.Drawing.Imaging;
namespacebase64_img
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
//图片转为base64编码的文本
privatevoidbutton1_Click(objectsender,EventArgse)
{
OpenFileDialogdlg=newOpenFileDialog();
dlg.Title="选择要转换的图片";
dlg.Filter="Imagefiles(*.jpg;*.bmp;*.gif)|*.jpg*.jpeg;*.gif;*.bmp|AllFiles(*.*)|*.*";
if(DialogResult.OK==dlg.ShowDialog())
{
ImgToBase64String(dlg.FileName);
}
}
//图片转为base64编码的文本
privatevoidImgToBase64String(stringImagefilename)
{
try
{
Bitmapbmp=newBitmap(Imagefilename);
this.pictureBox1.Image=bmp;
FileStreamfs=newFileStream(Imagefilename+".txt",FileMode.Create);
StreamWritersw=newStreamWriter(fs);
MemoryStreamms=newMemoryStream();
bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[]arr=newbyte[ms.Length];
ms.Position=0;
ms.Read(arr,0,(int)ms.Length);
ms.Close();
Stringstrbaser64=Convert.ToBase64String(arr);
sw.Write(strbaser64);
sw.Close();
fs.Close();
MessageBox.Show("转换成功!");
}
catch(Exceptionex)
{
MessageBox.Show("ImgToBase64String转换失败/nException:"+ex.Message);
}
}
//base64编码的文本转为图片
privatevoidbutton2_Click(objectsender,EventArgse)
{
OpenFileDialogdlg=newOpenFileDialog();
dlg.Title="选择要转换的base64编码的文本";
dlg.Filter="txtfiles|*.txt";
if(DialogResult.OK==dlg.ShowDialog())
{
Base64StringToImage(dlg.FileName);
}
}
//base64编码的文本转为图片
privatevoidBase64StringToImage(stringtxtFileName)
{
try
{
FileStreamifs=newFileStream(txtFileName,FileMode.Open,FileAccess.Read);
StreamReadersr=newStreamReader(ifs);
StringinputStr=sr.ReadToEnd();
byte[]arr=Convert.FromBase64String(inputStr);
MemoryStreamms=newMemoryStream(arr);
Bitmapbmp=newBitmap(ms);
bmp.Save(txtFileName+".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
//bmp.Save(txtFileName+".bmp",ImageFormat.Bmp);
//bmp.Save(txtFileName+".gif",ImageFormat.Gif);
//bmp.Save(txtFileName+".png",ImageFormat.Png);
ms.Close();
sr.Close();
ifs.Close();
this.pictureBox1.Image=bmp;
MessageBox.Show("转换成功!");
}
catch(Exceptionex)
{
MessageBox.Show("Base64StringToImage转换失败/nException:"+ex.Message);
}
}
}
}
PS:这里再为大家提供几款比较实用的base64在线编码解码工具供大家使用:
BASE64编码解码工具:
http://tools.jb51.net/transcoding/base64
在线图片转换BASE64工具:
http://tools.jb51.net/transcoding/img2base64
Base64在线编码解码UTF-8版:
http://tools.jb51.net/tools/base64_decode-utf8.php
Base64在线编码解码gb2312版:
http://tools.jb51.net/tools/base64_decode-gb2312.php
更多关于C#相关内容感兴趣的读者可查看本站专题:《C#编码操作技巧总结》、《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》
希望本文所述对大家C#程序设计有所帮助。