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);
            }
//将Base64String转为图片并保存
                        byte[] arr2 = Convert.FromBase64String(UserPhoto);
                        using (MemoryStream ms2 = new MemoryStream(arr2))
                        {
                            System.Drawing.Bitmap bmp2 = new System.Drawing.Bitmap(ms2);
                            ////只有把当前的图像复制一份,然后把旧的Dispose掉,那个文件就不被锁住了,
                            ////这样就可以放心覆盖原始文件,否则GDI+一般性错误(A generic error occurred in GDI+)
                            //System.Drawing.Bitmap bmpNew = new System.Drawing.Bitmap(bmp2);
                            //bmp2.Dispose();
                            //bmp2 = null;
                            bmp2.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            //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);
                            bmp2.Dispose();
                        }

 

posted @ 2023-11-06 17:18  恋上微笑的天使  阅读(1225)  评论(0编辑  收藏  举报