C#實現(xiàn)的圖片、string相互轉(zhuǎn)換類分享
C#中,Image為源自 Bitmap 和 Metafile 的類提供功能的抽象基類,也就是說更通用,當我們用Image.FromFile("xxx")時創(chuàng)建出來的是Image的某個派生類實體,所以我用Image作為參數(shù),而不是Bitmap之類的。
圖片在于string轉(zhuǎn)換的時候中間借助于MemorySteam和Byte數(shù)組,下面是我寫的FormatChange類,里面兩個互相轉(zhuǎn)換的過程。當然這里面也就包含了圖片與Byte[]數(shù)組的相互轉(zhuǎn)換嘍。
class FormatChange { public static string ChangeImageToString(Image image) { try { MemoryStream ms = new MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); string pic = Convert.ToBase64String(arr); return pic; } catch (Exception) { return "Fail to change bitmap to string!"; } } public static Image ChangeStringToImage(string pic) { try { byte[] imageBytes = Convert.FromBase64String(pic); //讀入MemoryStream對象 MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length); memoryStream.Write(imageBytes, 0, imageBytes.Length); //轉(zhuǎn)成圖片 Image image = Image.FromStream(memoryStream); return image; } catch (Exception) { Image image = null; return image; } } }
相關(guān)文章
C#用正則表達式Regex.Matches 方法檢查字符串中重復(fù)出現(xiàn)的詞
使用正則表達式用Regex類的Matches方法,可以檢查字符串中重復(fù)出現(xiàn)的詞,Regex.Matches方法在輸入字符串中搜索正則表達式的所有匹配項并返回所有匹配,本文給大家分享C#正則表達式檢查重復(fù)出現(xiàn)的詞,感興趣的朋友一起看看吧2024-02-02C#使用MiniExcel實現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)到Excel/CSV文件
MiniExcel是一個簡單、高效避免OOM的.NET處理Excel查、寫、填充數(shù)據(jù)的工具,這篇文章主要介紹了C#如何使用MiniExcel實現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)到Excel/CSV文件,需要的可以參考下2024-02-02

C#實現(xiàn)異步連接Sql Server數(shù)據(jù)庫的方法