匹配所有base64格式图片的正则表达式

 

匹配所有 base64 格式图片的正则表达式

 

 


                        string bucketName = _settingManager.GetSettingValue(AliOssConsts.BucketName);
                        var client = _aliOssManager.GetOssClient();


                        //匹配所有 base64 格式图片的正则表达式
                        string pattern = @"data:image/(?<type>.+?);base64,(?<data>[^""]+)";
                        Regex regex = new Regex(pattern, RegexOptions.Compiled);
                        MatchCollection matches = regex.Matches(entity.Content);
                        foreach (Match match in matches)
                        {
                            string type = match.Groups["type"].Value;
                            string data = match.Groups["data"].Value;
                            string fileRealGuid = $"kindeditor/image_base64/{System.Guid.NewGuid().ToString("N")}.{type}";

                            try
                            {

                                byte[] bytes = System.Convert.FromBase64String(data);
                                using (var stream = new MemoryStream(bytes))
                                {
                                    client.PutObject(bucketName, fileRealGuid, stream);
                                }
                                entity.Content = entity.Content.Replace(match.ToString(), $"https://aliyunosshost/{fileRealGuid}");

                            }
                            catch
                            {
                                entity.Content = entity.Content.Replace(match.ToString(), "");
                            }
                        }

 

© 版权声明

☆ END ☆
喜欢就点个赞吧
点赞1 分享
图片正在生成中,请稍后...