首页 > Windows开发 > 详细

C#中图片与BASE64码互相转换

时间:2016-01-29 16:25:17      阅读:303      评论:0      收藏:0      [点我收藏+]
 //保存目录
            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码互相转换

原文:http://www.cnblogs.com/JuneZhang/p/5169060.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!