图片帮助类

Posted xiemin-minmin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图片帮助类相关的知识,希望对你有一定的参考价值。

/// <summary>
    /// 图片操作帮助类
    /// </summary>
    public class ImgHelper
    {
        /// <summary>
        /// 从文件获取图片
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static Image GetImgFromFile(string fileName)
        {
            return Image.FromFile(fileName);
        }

        /// <summary>
        /// 从base64字符串读入图片
        /// </summary>
        /// <param name="base64">base64字符串</param>
        /// <returns></returns>
        public static Image GetImgFromBase64(string base64)
        {
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            Image img = Image.FromStream(memStream);

            return img;
        }

        /// <summary>
        /// 从URL格式的Base64图片获取真正的图片
        /// 即去掉data:image/jpg;base64,这样的格式
        /// </summary>
        /// <param name="base64Url">图片Base64的URL形式</param>
        /// <returns></returns>
        public static Image GetImgFromBase64Url(string base64Url)
        {
            string base64 = GetBase64String(base64Url);

            return GetImgFromBase64(base64);
        }

        /// <summary>
        /// 压缩图片
        /// 注:等比压缩
        /// </summary>
        /// <param name="img">原图片</param>
        /// <param name="width">压缩后宽度</param>
        /// <returns></returns>
        public static Image CompressImg(Image img, int width)
        {
            return CompressImg(img, width, (int)(((double)width) / img.Width * img.Height));
        }

        /// <summary>
        /// 压缩图片
        /// </summary>
        /// <param name="img">原图片</param>
        /// <param name="width">压缩后宽度</param>
        /// <param name="height">压缩后高度</param>
        /// <returns></returns>
        public static Image CompressImg(Image img, int width, int height)
        {
            Bitmap bitmap = new Bitmap(img, width, height);

            return bitmap;
        }

        /// <summary>
        /// 将图片转为base64字符串
        /// 默认使用jpg格式
        /// </summary>
        /// <param name="img">图片对象</param>
        /// <returns></returns>
        public static string ToBase64String(Image img)
        {
            return ToBase64String(img, ImageFormat.Jpeg);
        }

        /// <summary>
        /// 将图片转为base64字符串
        /// 使用指定格式
        /// </summary>
        /// <param name="img">图片对象</param>
        /// <param name="imageFormat">指定格式</param>
        /// <returns></returns>
        public static string ToBase64String(Image img, ImageFormat imageFormat)
        {
            MemoryStream memStream = new MemoryStream();
            img.Save(memStream, imageFormat);
            byte[] bytes = memStream.ToArray();
            string base64 = Convert.ToBase64String(bytes);

            return base64;
        }

        /// <summary>
        /// 将图片转为base64字符串
        /// 默认使用jpg格式,并添加data:image/jpg;base64,前缀
        /// </summary>
        /// <param name="img">图片对象</param>
        /// <returns></returns>
        public static string ToBase64StringUrl(Image img)
        {
            return "data:image/jpg;base64," + ToBase64String(img, ImageFormat.Jpeg);
        }

        /// <summary>
        /// 将图片转为base64字符串
        /// 使用指定格式,并添加data:image/jpg;base64,前缀
        /// </summary>
        /// <param name="img">图片对象</param>
        /// <param name="imageFormat">指定格式</param>
        /// <returns></returns>
        public static string ToBase64StringUrl(Image img, ImageFormat imageFormat)
        {
            string base64 = ToBase64String(img, imageFormat);

            return $"data:image/{imageFormat.ToString().ToLower()};base64,{base64}";
        }

        /// <summary>
        /// 获取真正的图片base64数据
        /// 即去掉data:image/jpg;base64,这样的格式
        /// </summary>
        /// <param name="base64UrlStr">带前缀的base64图片字符串</param>
        /// <returns></returns>
        public static string GetBase64String(string base64UrlStr)
        {
            string parttern = "^(data:image/.*?;base64,).*?$";

            var match = Regex.Match(base64UrlStr, parttern);
            if (match.Groups.Count > 1)
                base64UrlStr = base64UrlStr.Replace(match.Groups[1].ToString(), "");

            return base64UrlStr;
        }

        /// <summary>
        /// 将图片的URL或者Base64字符串转为图片并上传到服务器,返回上传后的完整图片URL
        /// </summary>
        /// <param name="imgBase64OrUrl">URL地址或者Base64字符串</param>
        /// <returns></returns>
        public static string GetImgUrl(string imgBase64OrUrl)
        {
            if (imgBase64OrUrl.Contains("data:image"))
            {
                Image img = ImgHelper.GetImgFromBase64Url(imgBase64OrUrl);
                string fileName = $"{GuidHelper.GenerateKey()}.jpg";

                string dir = Path.Combine(GlobalSwitch.WebRootPath, "Upload", "Img");
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);
                img.Save(Path.Combine(dir, fileName));

                return $"{GlobalSwitch.WebRootUrl}/Upload/Img/{fileName}";
            }
            else
                return imgBase64OrUrl;
        }

        #region 获取html中所有图片的url
        /// <summary>
        /// 获取html中所有图片的url
        /// </summary>
        /// <param name="sHtmlText"></param>
        /// <returns></returns>
        public static string[] GetImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签 
            Regex regImg = new Regex(@"<img[^<>]*?src[s	
]*=[s	
]*[""‘]?[s	
]*(?<imgUrl>[^s	
""‘<>]*)[^<>]*?/?[s	
]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串 
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表 
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }
        #endregion

        #region 更改html文本中的图片地址
        /// <summary>
        /// 更改html文本中的图片地址
        /// </summary>
        /// <param name="sHtmlText">带html的文本</param>
        /// <param name="thumbUrl">服务器上的文件路径</param>
        /// <returns></returns>
        public static string UpdateImageUrl(string sHtmlText, string thumbUrl)
        {
            // 定义正则表达式用来匹配 img 标签 
            Regex regImg = new Regex(@"<img[^<>]*?src[s	
]*=[s	
]*[""‘]?[s	
]*(?<imgUrl>[^s	
""‘<>]*)[^<>]*?/?[s	
]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串 
            MatchCollection matches = regImg.Matches(sHtmlText);
            // 取得匹配项列表
            foreach (Match match in matches)
            {
                if (sHtmlText.Contains(match.Groups["imgUrl"].Value))
                {
                    string uphtml = sHtmlText.Replace(match.Groups["imgUrl"].Value, thumbUrl);
                    return uphtml;
                }
            }
            return null;
        }
        #endregion

        #region 更改html文本中的Base64编码图片地址
        /// <summary>
        /// 更改html文本中的Base64编码图片地址
        /// </summary>
        /// <param name="sHtmlText">带html的文本</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static string UpdateImgBase64Url(string sHtmlText,string path="")
        {
            // 定义正则表达式用来匹配 img 标签 
            Regex regImg = new Regex(@"<img[^<>]*?src[s	
]*=[s	
]*[""‘]?[s	
]*(?<imgUrl>[^s	
""‘<>]*)[^<>]*?/?[s	
]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串 
            MatchCollection matches = regImg.Matches(sHtmlText);
            // 取得匹配项列表
            foreach (Match match in matches)
            {
                if (sHtmlText.Contains(match.Groups["imgUrl"].Value))
                {
                    var url= GetImgAllUrl(match.Groups["imgUrl"].Value, path.IsNullOrEmpty() ? "Upload/Img" : path);
                    string uphtml = sHtmlText.Replace(match.Groups["imgUrl"].Value, url);
                    return uphtml;
                }
            }
            return null;
        }
        #endregion

        #region 将图片的Base64字符串转为图片并上传到服务器,返回上传后的图片地址
        /// <summary>
        /// 将图片的URL或者Base64字符串转为图片并上传到服务器,返回上传后的图片地址
        /// </summary>
        /// <param name="imgBase64O">Base64字符串</param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static string GetImgAllUrl(string imgBase64O, string path="")
        {
            if (imgBase64O.Contains("data:image"))
            {
                Image img = ImgHelper.GetImgFromBase64Url(imgBase64O);
                string fileName = $"{GuidHelper.GenerateKey()}.jpg";
                string dir = Path.Combine(GlobalSwitch.WebRootPath, path.IsNullOrEmpty() ? "Upload/Img" : path);               
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);
                img.Save(Path.Combine(dir, fileName));
                return $"{GlobalSwitch.WebRootUrl}/{path}/{fileName}";
            }
            else
                return imgBase64O;
        }
        #endregion 
    }

以上是关于图片帮助类的主要内容,如果未能解决你的问题,请参考以下文章

十个html5代码片段,超实用,一定要收藏

片段 null 必须是公共静态类才能从实例状态正确重新创建

根据图片的url地址下载图片到本地保存代码片段

需要示例代码片段帮助

调用模板化成员函数:帮助我理解另一个 *** 帖子中的代码片段

如何在片段中使用按钮[关闭]