.NET指定图片地址下载并转换Base64字符串

需求描述

需要调用第三方图片上传接口上传图片,对方图片格式只能接收Base64字符串。所以我们需要将系统服务器的图片通过Url下载下来,然后转换成Base64字符串。接下来我们将使用HttpClient类库下载图片并将其转换为Base64格式的字符串。

代码示例

复制代码
        /// <summary>
        /// 获取图片的Base64字符串
        /// </summary>
        /// <param name="imageUrl">imageUrl</param>
        /// <returns></returns>
        public static async Task<string> GetImageBase64StringAsync(string imageUrl)
        {
            // 创建 HttpClient 实例
            using (var httpClient = new HttpClient())
            {
                // 下载图片
                var response = await httpClient.GetAsync(imageUrl);
                var contentStream = await response.Content.ReadAsStreamAsync();

                // 将图片转换为 Base64 格式的字符串
                using (var memoryStream = new MemoryStream())
                {
                    await contentStream.CopyToAsync(memoryStream);
                    string base64String = Convert.ToBase64String(memoryStream.ToArray());
                    return base64String;
                }
            }
        }

转换图片

原图地址:

https://rs1.huanqiucdn.cn/dp/api/files/imageDir/ce59747892d2b84f8c9b7f9d2561c765.png

方法调用

复制代码
var getImageBase64String = GetImageBase64StringAsync("https://rs1.huanqiucdn.cn/dp/api/files/imageDir/ce59747892d2b84f8c9b7f9d2561c765.png").ConfigureAwait(false).GetAwaiter().GetResult();

验证转换的Base64字符串是否能成功转成原图片

在线Base64转图片:https://www.lddgo.net/convert/base64-to-image

相关推荐
yngsqq1 小时前
(for 循环) VS (LINQ) 性能比拼 ——c#
c#·solr·linq
想做后端的小C2 小时前
C# 面向对象 构造函数带参无参细节解析
开发语言·c#·面向对象
炯哈哈2 小时前
【上位机——WPF】App.xml和Application类简介
xml·开发语言·c#·wpf·上位机
bestcxx2 小时前
c# UTC 时间赋值注意事项
c#·utc
酷炫码神2 小时前
C#运算符
开发语言·c#
zybsjn3 小时前
后端系统做国际化改造,生成多语言包
java·python·c#
敲代码的 蜡笔小新4 小时前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
yc_12244 小时前
SqlHelper 实现类,支持多数据库,提供异步操作、自动重试、事务、存储过程、分页、缓存等功能。
数据库·c#
Kookoos5 小时前
Redis + ABP vNext 构建分布式高可用缓存架构
redis·分布式·缓存·架构·c#·.net
Zhen (Evan) Wang7 小时前
ABP-Book Store Application中文讲解 - Part 2: The Book List Page
c#