C#中圖片、二進制與字符串的互相轉換辦法。本站提示廣大學習愛好者:(C#中圖片、二進制與字符串的互相轉換辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中圖片、二進制與字符串的互相轉換辦法正文
本文實例講述了C#中圖片、二進制與字符串的互相轉換辦法。分享給年夜家供年夜家參考,詳細以下:
protected void Button1_Click(object sender, EventArgs e) { //圖片轉二進制 byte[] imageByte = GetPictureData(Server.MapPath("./uploadfile/111.png")); //二進制轉換成字符串 string picStr = Convert.ToBase64String(imageByte); //輸入字符串 Response.Write(picStr); //字符串轉二進制 byte[] imageBytes = Convert.FromBase64String(picStr); //讀入MemoryStream對象 MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length); memoryStream.Write(imageBytes, 0, imageBytes.Length); //二進制轉成圖片保留 System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream); image.Save(Server.MapPath("./uploadfile/222.png")); } /// <summary> /// 二進制流轉圖片 /// </summary> /// <param name="streamByte">二進制流</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> /// 圖片轉二進制 /// </summary> /// <param name="imagepath">圖片地址</param> /// <returns>二進制</returns> public byte[] GetPictureData(string imagepath) { //依據圖片文件的途徑應用文件流翻開,並保留為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> /// 圖片轉二進制 /// </summary> /// <param name="imgPhoto">圖片對象</param> /// <returns>二進制</returns> public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto) { //將Image轉換成流數據,並保留為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:這裡小編再給年夜家推舉本站的一款圖片轉BASE64格局的在線轉換對象,異常具有適用價值:
在線圖片轉換BASE64對象:
http://tools.jb51.net/transcoding/img2base64
願望本文所述對年夜家C#法式設計有所贊助。