C# base64編碼的文本與圖片互轉


       /// <summary>  
        /// base64編碼的文本轉為圖片  
        /// </summary>  
        /// <param name="txtFilePath">文件相對路徑(存到服務器上)</param>  
        /// <param name="str">圖片字符串</param>  
        private void Base64StringToImage(string txtFilePath, string str)
        {
            try
            {
                String inputStr = str;
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);

                bmp.Save(System.Web.HttpContext.Current.Server.MapPath(txtFilePath) + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);  
                //bmp.Save(txtFileName + ".gif", ImageFormat.Gif);  
                //bmp.Save(txtFileName + ".png", ImageFormat.Png);  
                ms.Close();
                //imgPhoto.ImageUrl = txtFilePath + ".jpg";  
                //MessageBox.Show("轉換成功!");  
            }
            catch (Exception ex)
            {

            }
        }
       protected string ImgToBase64String(string ImagePath)
        {
            try
            {
                Bitmap bmp = new Bitmap(System.Web.HttpContext.Current.Server.MapPath(ImagePath));
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM