C#中圖片、二進(jìn)制與字符串的相互轉(zhuǎn)換方法
本文實(shí)例講述了C#中圖片、二進(jìn)制與字符串的相互轉(zhuǎn)換方法。分享給大家供大家參考,具體如下:
protected void Button1_Click(object sender, EventArgs e) { //圖片轉(zhuǎn)二進(jìn)制 byte[] imageByte = GetPictureData(Server.MapPath("./uploadfile/111.png")); //二進(jìn)制轉(zhuǎn)換成字符串 string picStr = Convert.ToBase64String(imageByte); //輸出字符串 Response.Write(picStr); //字符串轉(zhuǎn)二進(jìn)制 byte[] imageBytes = Convert.FromBase64String(picStr); //讀入MemoryStream對象 MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length); memoryStream.Write(imageBytes, 0, imageBytes.Length); //二進(jìn)制轉(zhuǎn)成圖片保存 System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream); image.Save(Server.MapPath("./uploadfile/222.png")); } /// <summary> /// 二進(jìn)制流轉(zhuǎn)圖片 /// </summary> /// <param name="streamByte">二進(jìn)制流</param> /// <returns>圖片</returns> public System.Drawing.Image ReturnPhoto(byte[] streamByte) { System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); return img; } /// <summary> /// 圖片轉(zhuǎn)二進(jìn)制 /// </summary> /// <param name="imagepath">圖片地址</param> /// <returns>二進(jìn)制</returns> public byte[] GetPictureData(string imagepath) { //根據(jù)圖片文件的路徑使用文件流打開,并保存為byte[] FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重載方法 byte[] byData = new byte[fs.Length]; fs.Read(byData, 0, byData.Length); fs.Close(); return byData; } /// <summary> /// 圖片轉(zhuǎn)二進(jìn)制 /// </summary> /// <param name="imgPhoto">圖片對象</param> /// <returns>二進(jìn)制</returns> public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto) { //將Image轉(zhuǎn)換成流數(shù)據(jù),并保存為byte[] MemoryStream mstream = new MemoryStream(); imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp); byte[] byData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byData, 0, byData.Length); mstream.Close(); return byData; }
PS:這里小編再給大家推薦本站的一款圖片轉(zhuǎn)BASE64格式的在線轉(zhuǎn)換工具,非常具有實(shí)用價值:
在線圖片轉(zhuǎn)換BASE64工具:
http://tools.jb51.net/transcoding/img2base64
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《C#常見控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計入門教程》及《C#程序設(shè)計之線程使用技巧總結(jié)》
希望本文所述對大家C#程序設(shè)計有所幫助。
相關(guān)文章
異步/多線程/任務(wù)/并行編程之一:如何選擇合適的多線程模型?
本篇文章小編為大家介紹,異步/多線程/任務(wù)/并行編程之一:如何選擇合適的多線程模型?需要的朋友參考下2013-04-04c#之獲取本機(jī)主機(jī)名的四種方式總結(jié)
這篇文章主要介紹了c#之獲取本機(jī)主機(jī)名的四種方式總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Unity3D使用鼠標(biāo)旋轉(zhuǎn)縮放平移視角
這篇文章主要為大家詳細(xì)介紹了Unity3D使用鼠標(biāo)旋轉(zhuǎn)縮放平移視角,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07