码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-01-29 16:25:28      阅读:414      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!