引用1.0.3版本或以上的Wesky.Net.OpenTools 包
1.0.3 版本提供图片转Base64字符串方案,并提供根据后缀名自动识别Mime类型,合成标准URI
该nuget包支持.net framework4.6.1和以上、.net core2和以上、.net 5和以上所有环境使用。
开源项目地址:
Gitee:https://gitee.com/dreamer_j/open-tools.git
Github:https://github.com/LittleLittleRobot/OpenTools.git
引用1.0.3版本或以上的Wesky.Net.OpenTools 包
1.0.3 版本提供图片转Base64字符串方案,并提供根据后缀名自动识别Mime类型,合成标准URI
开源项目地址:
Gitee:https://gitee.com/dreamer_j/open-tools.git
Github:https://github.com/LittleLittleRobot/OpenTools.git
为了简单操作,我直接把base64字符串,外面套一层,让它支持md文件展示。图片地址为桌面上个人公众号图片地址,格式类型为jpg
static void Main(string[] args){var file = @"xxx.jpg";var data = Wesky.Net.OpenTools.Converter.ImageConvert.ConvertImageToBase64(file);var mdString = $"";Console.WriteLine(mdString);}
运行程序,得到base64字符串.base64字符串。base64字符串,使用格式:的形式,即可被markdown所识别,并显示未原始图片。
复制该全部字符串内容,粘贴到任意markdown文本编辑器内。以下我用Typora实验,可以看到自动解析出文本,并显示了我用来实验的图片。
核心代码解析:
////// 将图片文件转换为 Base64 编码的字符串。/// Converts an image file to a Base64-encoded string.////// 图片文件的路径。Path to the image file.///返回 Base64 编码的图片字符串。Returns a Base64-encoded image string. public static string ConvertImageToBase64(string imagePath){if (!File.Exists(imagePath)){throw new FileNotFoundException("指定的图片路径不存在。Specified image path does not exist.");}byte[] imageBytes = File.ReadAllBytes(imagePath);string mimeType = GetMimeType(imagePath);string base64String = Convert.ToBase64String(imageBytes);return $"data:{mimeType};base64,{base64String}";}
支持图片格式:
case ".bmp":return "image/bmp";case ".gif":return "image/gif";case ".jpg":case ".jpeg":return "image/jpeg";case ".png":return "image/png";case ".tif":case ".tiff":return "image/tiff";case ".ico":return "image/x-icon";
