using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; namespace Appointment.Entity { public static class PicHelper { /// /// 获取图片域名 /// /// public static string GetPicDomain() { string value = string.Empty; using (System.IO.StreamReader file = System.IO.File.OpenText("appsettings.json")) { using JsonTextReader reader = new JsonTextReader(file); JObject o = (JObject)JToken.ReadFrom(reader); value = Convert.ToString(o["WebApiDomain"]); } if (string.IsNullOrWhiteSpace(value)) throw new Exception("配置信息中缺少WebApiDomain"); return value; } /// /// 获取图片保存服务器完整路径 /// /// public static string GetPicRootPath() { string value = string.Empty; using (System.IO.StreamReader file = System.IO.File.OpenText("appsettings.json")) { using JsonTextReader reader = new JsonTextReader(file); JObject o = (JObject)JToken.ReadFrom(reader); value = Convert.ToString(o["PicRootPath"]); } if (string.IsNullOrWhiteSpace(value)) throw new Exception("配置信息中缺少PicRootPath"); return value; } /// /// 保存图片 /// /// 图片BASE64 /// NULL-保存图片异常,""-没有图片,其他-保存后的路径 public static ApiResult SavePic(string base64str) { try { if (string.IsNullOrWhiteSpace(base64str)) return ApiResult.Success(string.Empty); if (base64str.ToLower().IndexOf("imgfile") > 0) return ApiResult.Success(base64str.Substring(base64str.ToLower().IndexOf("imgfile") - 1)); DateTime now = DateTime.Now; var rd = new Random().Next(100, 999); string filePath = $"/ImgFile/{now:yyyyMM}"; string fileName = $"{now:yyyyMMddHHmmssfff}{rd}"; base64str = base64str.Substring(base64str.IndexOf(",") + 1).Trim('\0'); byte[] arr = Convert.FromBase64String(base64str); using (MemoryStream ms = new MemoryStream(arr)) { if (!Directory.Exists(GetPicRootPath() + filePath)) Directory.CreateDirectory(GetPicRootPath() + filePath); Bitmap bmp = new Bitmap(ms); ImageCodecInfo myImageCodecInfo = GetEnoderInfo(bmp.RawFormat.ToString().ToLower()); if (bmp.RawFormat.ToString().ToLower().Contains("jpeg")) { fileName = $"{fileName}.jpg"; myImageCodecInfo = GetEnoderInfo("png"); } else { fileName = $"{fileName}.{bmp.RawFormat}"; } EncoderParameters destEncParams = new EncoderParameters(1); destEncParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100); bmp.Save($"{GetPicRootPath()}{filePath}/{fileName}", myImageCodecInfo, destEncParams); ms.Close(); } return ApiResult.Success($"{filePath}/{fileName}"); } catch (Exception ex) { return ApiResult.Failed("保存图片失败,失败信息:" + ex.Message); } } #region private private static ImageCodecInfo GetEnoderInfo(string mineType) { ImageCodecInfo[] myEncoders = ImageCodecInfo.GetImageEncoders(); foreach (System.Drawing.Imaging.ImageCodecInfo myEncoder in myEncoders) if (myEncoder.MimeType.Contains(mineType)) return myEncoder; return null; } #endregion } }