將圖片轉化爲Base64字符串的流程是:首先使用BinaryFormatter將圖片文件序列化爲二進制數據,而後使用Convert類的ToBase64String方法。將Base64字符串轉換爲圖片的流程正好相反:使用Convert類的FromBase64String獲得圖片文件的二進制數據,而後使用BinaryFormatter反序列化方法。ide
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;
}
|