C# 图片与Base64互转及存储

2020年4月16日 3558点热度 0人点赞 0条评论
内容目录

下面是一张图片的 base64 编码
file

下面代码是很久前写的了,暂时不改,为了速度,请修改字符串操作部分的代码。

        /// 
        /// base64转为图片存储到本地
        /// 
        /// 
        /// 
        /// 
        public static async Task ImageToFile(string base64,string imagesPath)
        {
            if (String.IsNullOrEmpty(base64)) return null;

            // 这样去除替换前面的 data:image/jpg;base64,
            // 替换的效率高,应该使用索引删除
            string[] imageBases = base64.Split("base64,");
            if (imageBases.Length <= 1)
                return null;

            if (!Directory.Exists(imagesPath))
                Directory.CreateDirectory(imagesPath);

            byte[] response = Convert.FromBase64String(imageBases[1]);

            if (response.Length <= 0) return null;

            string name = DateTime.Now.Ticks.ToString();

            if (imageBases[0] == "data:image/jpg;")
                name += ".jpg";
            else if (imageBases[0] == "data:image/png;")
                name += ".png";
            else
                return null;

            using (FileStream fs = new FileStream(Path.Combine(imagesPath, "/", name), FileMode.Create, FileAccess.Write))
            {
                await fs.WriteAsync(response);
                await fs.FlushAsync();
                fs.Close();
            }
            return name;
        }

Convert.ToBase64String() 可以将字符串或 byte[] 转为 Base64 图片字符串。

获取图片 md5 值

        /// 
        /// 获取文件MD5值
        /// 
        /// 文件绝对路径
        /// MD5值
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }

图片文件生成base64:

        private static string GetBase64(string imagePath)
        {
            string result = Convert.ToBase64String(File.ReadAllBytes(imagePath));
            result = result.Replace("data:image/jpeg;base64,", string.Empty);
            //byte[] base64 = Convert.FromBase64String(result);
            return result;
        }

base64转存图片到本地

static void Test(string base64){
 if (String.IsNullOrEmpty(base64)) return;
            byte[] response = Convert.FromBase64String(base64);

            if (!(response.Length > 0)) return;
            if (!Directory.Exists(dirpath)) Directory.CreateDirectory(dirpath);

            using (FileStream fs = new FileStream(dirpath + "/" + "原图" + aa + ".jpg", FileMode.Create, FileAccess.Write))
            {
                await fs.WriteAsync(response);
                await fs.FlushAsync();
                fs.Close();
            }
}

痴者工良

高级程序员劝退师

文章评论