C# Base64和图片转换

Base64和图片转换

    public class FileHelper
    {
        /// <summary>
        /// 通过路径获取文件并处理成Base64
        /// </summary>
        /// <param name="filePath">图片路径</param>
        /// <param name="isVirtualPath">是否虚拟路径</param>
        /// <returns></returns>
        public static string ImgToBase64(string filePath, bool isVirtualPath = true)
        {
            string basePath = AppContext.BaseDirectory;//获取程序根目录
            if (isVirtualPath)
            {
                var s1 = Directory.GetCurrentDirectory();
                filePath = $"{basePath}/{filePath}";
            }
            //照片旋转处理
            // RemoveRotateFlip(FilePath);

            if (System.IO.File.Exists(filePath))
            {
                #region Bitmap

                //Bitmap bmp = new Bitmap(filePath);
                //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();
                //string strbaser64 = Convert.ToBase64String(arr);
                //return strbaser64;

                #endregion

                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                fs.Seek(0, SeekOrigin.Begin);
                //图片转base64  
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                return Convert.ToBase64String(bytes);
            }
            return "";
        }

        /// <summary>
        /// 将Base64处理成图片文件保存到本地
        /// </summary>
        /// <param name="uploadPath">图片保存地址,如:/Content/Images/10000.png</param>
        /// <param name="imgBase64">base64字符串</param>
        /// <returns>返回相对路径</returns>
        public static string Base64ToImagePath(string imgBase64,string uploadPath = "uploadImgPath")
        {
            string basePath = Directory.GetCurrentDirectory(); //AppContext.BaseDirectory;
            string DatePath = DateTime.Now.ToString("yyyyMMdd");//日期子目录
            //AppName = hostingEnvironment.ApplicationName,
            //    ContentRootPath = hostingEnvironment.ContentRootPath,
            //    WebRootPath = hostingEnvironment.WebRootPath,
            //    EnvironmentName = hostingEnvironment.EnvironmentName,

            uploadPath = uploadPath + "/" + DatePath + "/"; //所要保存的相对路径
            string folderPath = basePath + "\\" + uploadPath +"\\";
            //目录
            string tmpRootDir = Path.GetDirectoryName(folderPath);

            //System.Web.HttpContext context = System.Web.HttpContext.Current;
            //tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(uploadPath); //获取程序根目录 
            //if (context != null)
            //{
            //    tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(uploadPath); //获取程序根目录 
            //}
            ////异步情况
            //else
            //{
            //    tmpRootDir=System.Web.HttpRuntime.AppDomainAppPath + uploadPath;
            //}
            if (!Directory.Exists(tmpRootDir))
            {
                Directory.CreateDirectory(tmpRootDir);
            }

            Thread.Sleep(1);
            string imgName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + GetRandomString(10);
            string fileName = uploadPath +"/"+ imgName + ".jpg";//所要保存的相对路径及名字;//声明一个string类型的相对路径

            string imageFullPath = tmpRootDir +"\\"+ imgName + ".jpg"; //转换成绝对路径,保存图片

            //取图片的后缀格式
            //string hz = ImgBase64.Split(',')[0].Split(';')[0].Split('/')[1];
            //string[] str = ImgBase64.Split(',');  //base64Str为base64完整的字符串,先处理一下得到我们所需要的字符串

            imgBase64 = imgBase64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "").Replace("data:image/jpng;base64,", "");//将base64头部信息替换
            byte[] imageBytes = Convert.FromBase64String(imgBase64);
            //读入MemoryStream对象
            MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
            memoryStream.Write(imageBytes, 0, imageBytes.Length);
            //  转成图片
            Image image = Image.FromStream(memoryStream);
            //   图片名称
            //  string iname = DateTime.Now.ToString("yyMMddhhmmss");
            image.Save(imageFullPath);  // 将图片存到本地Server.MapPath("pic\\") + iname + "." + hz

            //照片旋转处理
            //RemoveRotateFlip(imagesurl2);

            return fileName;
        }

        /// <summary>
        /// Base64转图片
        /// </summary>
        /// <param name="base64"></param>
        /// <param name="fullPath">全路径</param>
        public static void Base64ToImage(string base64, string fullPath)
        {
            try
            {
                //取图片的后缀格式
                //string hz = ImgBase64.Split(',')[0].Split(';')[0].Split('/')[1];
                //string[] str = ImgBase64.Split(',');  //base64Str为base64完整的字符串,先处理一下得到我们所需要的字符串

                base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "").Replace("data:image/jpng;base64,", "");//将base64头部信息替换
                byte[] imageBytes = Convert.FromBase64String(base64);
                MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
                memoryStream.Write(imageBytes, 0, imageBytes.Length);

                #region 方法1.Image保存

                //Image image = Image.FromStream(memoryStream);
                //image.Save(fullPath);

                #endregion

                //方法2
                Bitmap bp = new Bitmap(memoryStream);
                bp.Save(fullPath);//注意保存路径
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取一个随机数
        /// </summary>
        /// <param name="Num"></param>
        /// <returns></returns>
        public static string GetRandomString(int Num)
        {
            string res = "";
            char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                           'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                           'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                           'U', 'V', 'W', 'X', 'Y', 'Z'};
            Random random = new Random();
            for (var i = 0; i < Num; i++)
            {
                int num = random.Next(str.Length);
                res += str[num];
            }

            return res;
        }

        /// <summary>
        /// 将旋转照片恢复正常
        /// </summary>
        /// <param name="srcPathName"></param>
        public static void RemoveRotateFlip(string srcPathName)
        {
            Image image = new Bitmap(srcPathName);
            //初始化图片对象 
            foreach (var p in image.PropertyItems)
            {
                if (p.Id == 0x112)
                {
                    var rft = p.Value[0] == 6 ? RotateFlipType.Rotate90FlipNone
                            : p.Value[0] == 3 ? RotateFlipType.Rotate180FlipNone
                            : p.Value[0] == 8 ? RotateFlipType.Rotate270FlipNone
                            : p.Value[0] == 1 ? RotateFlipType.RotateNoneFlipNone
                            : RotateFlipType.RotateNoneFlipNone;
                    p.Value[0] = 0;  //旋转属性值设置为不旋转
                    image.SetPropertyItem(p); //回拷进图片流
                    image.RotateFlip(rft);
                    image.Save(srcPathName, ImageFormat.Jpeg); //重新保存为正常的图片
                    image.Dispose(); //释放图片对象资源
                                     //File.Delete(srcPathName);//这里是否删除,根据业务需要定
                }
            }
        }

        /// <summary>
        /// MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5Security(string str)
        {
            var strSecurityPwd = string.Empty;
            try
            {
                //using (var md5 = MD5.Create())
                //{
                //    var result = md5.ComputeHash(Encoding.ASCII.GetBytes(input));
                //    var strResult = BitConverter.ToString(result);
                //    return strResult.Replace("-", "");
                //}
                using (var md5 = MD5.Create())
                {
                    byte[] bytValue, bytHash;
                    bytValue = System.Text.Encoding.UTF8.GetBytes(str);
                    bytHash = md5.ComputeHash(bytValue);
                    md5.Clear();
                    string sTemp = "";
                    for (int i = 0; i < bytHash.Length; i++)
                    {
                        sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
                    }
                    strSecurityPwd = sTemp.ToLower();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return strSecurityPwd;
        }


        private static string DESKey = "Jiuyi8899";

        #region ========加密========
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, DESKey);
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            //string value = Md5.Md5Hash(sKey).Substring(0, 8);
            string value = Md5Security(sKey);
            des.Key = ASCIIEncoding.ASCII.GetBytes(value);
            des.IV = ASCIIEncoding.ASCII.GetBytes(value);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            if (!string.IsNullOrEmpty(Text))
            {
                return Decrypt(Text, DESKey);
            }
            else
            {
                return "";
            }
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            //string value = Md5.Md5Hash(sKey).Substring(0, 8);
            string value = Md5Security(sKey);
            des.Key = ASCIIEncoding.ASCII.GetBytes(value);
            des.IV = ASCIIEncoding.ASCII.GetBytes(value);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion

    }
View Code

 

posted @ 2022-05-30 10:30  bxzjzg  阅读(122)  评论(0编辑  收藏  举报