c# Base64編碼和圖片的互相轉(zhuǎn)換代碼
事出有因
我們已經(jīng)做了一個(gè)編輯器,這個(gè)編輯器可以以xml格式存儲(chǔ)一些信息。在存儲(chǔ)圖片信息時(shí)我們碰到了一些問(wèn)題。我們本來(lái)在xml信息中存儲(chǔ)的是圖片的路徑,然而一旦客戶(hù)把這個(gè)信息copy到其他電腦上而沒(méi)有同時(shí)copy相關(guān)的圖片時(shí),就會(huì)出現(xiàn)一些問(wèn)題。
后來(lái),我們把圖片數(shù)據(jù)轉(zhuǎn)換為Base64編碼,替代了原先存儲(chǔ)圖片路徑的方式。
轉(zhuǎn)換流程
將圖片轉(zhuǎn)化為Base64字符串的流程是:首先使用BinaryFormatter將圖片文件序列化為二進(jìn)制數(shù)據(jù),然后使用Convert類(lèi)的ToBase64String方法。將Base64字符串轉(zhuǎn)換為圖片的流程正好相反:使用Convert類(lèi)的FromBase64String得到圖片文件的二進(jìn)制數(shù)據(jù),然后使用BinaryFormatter反序列化方法。
/// <summary> /// 將圖片數(shù)據(jù)轉(zhuǎn)換為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字符串轉(zhuǎn)換為圖片 /// </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; }
運(yùn)行結(jié)果
- C# 圖片與Base64碼的相互轉(zhuǎn)化問(wèn)題(代碼詳解)
- c#和java base64不一致的解決方法
- C#實(shí)現(xiàn)字符串與圖片的Base64編碼轉(zhuǎn)換操作示例
- C#實(shí)現(xiàn)Base64處理的加密解密,編碼解碼示例
- C#編寫(xiě)的Base64加密和解密類(lèi)
- C#解碼base64編碼二進(jìn)制數(shù)據(jù)的方法
- asp.C#實(shí)現(xiàn)圖片文件與base64string編碼解碼
- c# 實(shí)現(xiàn)文件上傳下載功能的實(shí)例代碼
- C#實(shí)現(xiàn)的文件上傳下載工具類(lèi)完整實(shí)例【上傳文件自動(dòng)命名】
- C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼
- C#實(shí)現(xiàn)Web文件上傳的兩種方法實(shí)例代碼
- c# 用Base64實(shí)現(xiàn)文件上傳
相關(guān)文章
C# winForm實(shí)現(xiàn)的氣泡提示窗口功能示例
這篇文章主要介紹了C# winForm實(shí)現(xiàn)的氣泡提示窗口功能,涉及C# winForm窗口屬性與設(shè)置相關(guān)操作技巧,需要的朋友可以參考下2018-03-03C#中的Timer和DispatcherTimer使用實(shí)例
這篇文章主要介紹了C#中的Timer和DispatcherTimer使用實(shí)例,本文分別給出它們的使用代碼實(shí)例,需要的朋友可以參考下2015-01-01使用XmlSerializer序列化List對(duì)象成XML格式(list對(duì)象序列化)
這篇文章主要介紹了使用XmlSerializer序列化List對(duì)象成XML格式(list對(duì)象序列化),需要的朋友可以參考下2014-03-03