图片URL转成Base64字符串
/// <summary> /// 通过Url获取到Image格式的文件 /// </summary> /// <param name="url"></param> /// <returns></returns> public static Image UrlToImage(string url) { WebClient mywebclient = new WebClient(); byte[] Bytes = mywebclient.DownloadData(url); using (MemoryStream ms = new MemoryStream(Bytes)) { Image outputImg = Image.FromStream(ms); return outputImg; } } /// <summary> /// 再将Iamge文件转为Base64字符串 /// </summary> /// <param name="img"></param> /// <returns></returns> public static string BitmapToBase64(Image img) { System.Drawing.Bitmap bitMap = new System.Drawing.Bitmap(img); string imgBase64 = string.Empty; using (MemoryStream memoryStream = new MemoryStream()) { bitMap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] buffer = new byte[memoryStream.Length]; memoryStream.Position = 0; memoryStream.Read(buffer, 0, (int)memoryStream.Length); memoryStream.Close(); imgBase64 = Convert.ToBase64String(buffer); } return imgBase64; }
Base64字符串转成图片并保存
/// <summary> /// 将Base64String转为图片并保存 /// </summary> /// <param name="imgBase64"></param> public static void Base64ToImage(string imgBase64) { string format; string imgPath = Directory.GetCurrentDirectory() + "\" + DateTime.Now.ToString("yyyyMMddHHmmss"); byte[] buffer = Convert.FromBase64String(imgBase64); using (MemoryStream memoryStream = new MemoryStream(buffer)) { System.Drawing.Bitmap bitMap = new System.Drawing.Bitmap(memoryStream); System.Drawing.Imaging.ImageFormat imgFormat = GetImageFormat(memoryStream, out format); imgPath = imgPath + format; bitMap.Save(imgPath, imgFormat); bitMap.Dispose(); } } /// <summary> /// 获取Image图片格式 /// </summary> /// <param name="file"></param> /// <param name="format"></param> /// <returns></returns> private static System.Drawing.Imaging.ImageFormat GetImageFormat(MemoryStream file, out string format) { byte[] sb = new byte[2]; //这次读取的就是直接0-1的位置长度了. file.Read(sb, 0, sb.Length); //根据文件头判断 string strFlag = sb[0].ToString() + sb[1].ToString(); //察看格式类型 switch (strFlag) { //JPG格式 case "255216": format = ".jpg"; return System.Drawing.Imaging.ImageFormat.Jpeg; //GIF格式 case "7173": format = ".gif"; return System.Drawing.Imaging.ImageFormat.Gif; //BMP格式 case "6677": format = ".bmp"; return System.Drawing.Imaging.ImageFormat.Bmp; //PNG格式 case "13780": format = ".png"; return System.Drawing.Imaging.ImageFormat.Png; //其他格式 default: format = ".jpg"; return System.Drawing.Imaging.ImageFormat.Jpeg; } }
调用
static void Main(string[] args) { //string imgUrl = "D:\c29e09b0-e5f4-43fa-9ded-8f9865a2e8d4.jpg"; //string imgUrl = "https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png"; string imgUrl = "http://file02.16sucai.com/d/file/2015/0408/779334da99e40adb587d0ba715eca102.jpg";//图片可以是本地磁盘地址、可以是http和https地址 Image img = UrlToImage(imgUrl);//转成Image格式 string imgBase64 = BitmapToBase64(img); //注意:生成的Base64字符串加上 data:image/jpeg;base64, 可以在前端识别 Base64ToImage( imgBase64);//生成图片并保存 Console.ReadKey(); }