c#通常使用兩個方法來處理base64字符串
1:Convert.ToBase64String
2:Convert.FromBase64String
參考案例:將圖像轉化為base64字符串,再將base64字符串轉換為圖像
private void button4_Click(object sender, EventArgs e)
{
//處理圖像
string fileNmae = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileNmae = openFileDialog1.FileName;
}
else
{
fileNmae = @"d:\對聯1.jpg";
}
Bitmap bmp = new Bitmap(fileNmae);
BinaryFormatter bin = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
try
{
bin.Serialize(mem, bmp);
String strString = Convert.ToBase64String(mem.GetBuffer(), 0, Convert.ToInt32(mem.Length));
this.textBox1.Text = strString;
Application.DoEvents();
}
catch (Exception ex)
{
throw (ex);
}
finally
{
mem.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
byte[] bits = Convert.FromBase64String(this.textBox1.Text);
MemoryStream mem = new MemoryStream(bits);
BinaryFormatter bin = new BinaryFormatter();
try
{
object obj = ((object)(bin.Deserialize(mem)));
this.pictureBox1.Image = (Bitmap)obj;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
mem.Close();
}
}