C#中图片与BASE64码互相转换
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中图片与BASE64码互相转换相关的知识,希望对你有一定的参考价值。
//保存目录 string dir = "/upload/user/head"; //站点文件目录 string fileDir = HttpContext.Current.Server.MapPath("~" + dir); //文件名称 string fileName = "headdemo" + DateTime.Now.ToString("yyyyMMddHHmmssff"); //保存文件所在站点位置 string filePath = Path.Combine(fileDir, fileName); if (!System.IO.Directory.Exists(fileDir)) System.IO.Directory.CreateDirectory(fileDir); //读图片转为Base64String System.Drawing.Bitmap bmp1 = new System.Drawing.Bitmap(Path.Combine(fileDir, "default.jpg")); using (MemoryStream ms1 = new MemoryStream()) { bmp1.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr1 = new byte[ms1.Length]; ms1.Position = 0; ms1.Read(arr1, 0, (int)ms1.Length); ms1.Close(); UserPhoto = Convert.ToBase64String(arr1); } //将Base64String转为图片并保存 byte[] arr2 = Convert.FromBase64String(UserPhoto); using (MemoryStream ms2 = new MemoryStream(arr2)) { System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2); bmp2.Save(filePath + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); //bmp2.Save(filePath + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp); //bmp2.Save(filePath + ".gif", System.Drawing.Imaging.ImageFormat.Gif); //bmp2.Save(filePath + ".png", System.Drawing.Imaging.ImageFormat.Png); }
以上是关于C#中图片与BASE64码互相转换的主要内容,如果未能解决你的问题,请参考以下文章