C#實(shí)現(xiàn)的圖片、string相互轉(zhuǎn)換類分享
C#中,Image為源自 Bitmap 和 Metafile 的類提供功能的抽象基類,也就是說更通用,當(dāng)我們用Image.FromFile("xxx")時創(chuàng)建出來的是Image的某個派生類實(shí)體,所以我用Image作為參數(shù),而不是Bitmap之類的。
圖片在于string轉(zhuǎn)換的時候中間借助于MemorySteam和Byte數(shù)組,下面是我寫的FormatChange類,里面兩個互相轉(zhuǎn)換的過程。當(dāng)然這里面也就包含了圖片與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;
}
}
}
- C#簡易圖片格式轉(zhuǎn)換器實(shí)現(xiàn)方法
- C#實(shí)現(xiàn)字符串與圖片的Base64編碼轉(zhuǎn)換操作示例
- C#實(shí)現(xiàn)把圖片轉(zhuǎn)換成二進(jìn)制以及把二進(jìn)制轉(zhuǎn)換成圖片的方法示例
- C#中圖片.BYTE[]和base64string的轉(zhuǎn)換方法
- 詳談C# 圖片與byte[]之間以及byte[]與string之間的轉(zhuǎn)換
- C#中圖片、二進(jìn)制與字符串的相互轉(zhuǎn)換方法
- c# Base64編碼和圖片的互相轉(zhuǎn)換代碼
- C# 圖片格式轉(zhuǎn)換的實(shí)例代碼
相關(guān)文章
C#用正則表達(dá)式Regex.Matches 方法檢查字符串中重復(fù)出現(xiàn)的詞
使用正則表達(dá)式用Regex類的Matches方法,可以檢查字符串中重復(fù)出現(xiàn)的詞,Regex.Matches方法在輸入字符串中搜索正則表達(dá)式的所有匹配項(xiàng)并返回所有匹配,本文給大家分享C#正則表達(dá)式檢查重復(fù)出現(xiàn)的詞,感興趣的朋友一起看看吧2024-02-02
C#使用MiniExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)到Excel/CSV文件
MiniExcel是一個簡單、高效避免OOM的.NET處理Excel查、寫、填充數(shù)據(jù)的工具,這篇文章主要介紹了C#如何使用MiniExcel實(shí)現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)到Excel/CSV文件,需要的可以參考下2024-02-02
C#實(shí)現(xiàn)異步連接Sql Server數(shù)據(jù)庫的方法

