分为两种情况:
第一种情况:是图片保存在本地:
获取图片路径,得到图片的根路径,
AppDomain.CurrentDomain.BaseDirectory
表示当前应用程序域的基本目录,也就是应用程序的根目录
Path.Combine()
方法则用于将多个字符串片段合并成一个完整的路径字符串
File.ReadAllBytes(),它接受一个文件路径作为参数,并返回该路径指定文件的所有字节内容。返回的结果是一个字节数组,其中每个字节表示文件中对应位置的数据。
string image = "412326199001243338.jpg";
获取到图片的详细路径
string BasePath = System.AppDomain.CurrentDomain.BaseDirectory; //根路径
string PeopleUrl = BasePath + "UploadFile/People/";
string filePath = PeopleUrl + image;
string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
byte[] imageBytes = File.ReadAllBytes(fullPath);
string ImageBase64 = Convert.ToBase64String(imageBytes);
第二种情况:是图片是服务器或者网络上的图片
WebClient
类从指定的 URL 下载数据并将其转换为字节数组。
创建了一个 WebClient
对象,然后使用 DownloadData()
方法从 Image
参数指定的 URL 下载数据(这里假设 Image
是一个字符串变量,存储了一个有效的 URL 地址)。下载的结果以字节数组的形式返回,赋值给 Bytes
变量。
string Image ="图片路径";//比如:http://www.bai/dsdasd.jpg
// 将图片转换为base64编码
WebClient mywebclient = new WebClient();
byte[] Bytes = mywebclient.DownloadData(Image);
string ImageBase64 = Convert.ToBase64String(Bytes);