话不多说,直接上代码:
其中Imagefilename是文件完整路径
public string ToBase64()
{
try
{
string Imagefilename = "C:/Users/12205/source/repos/WebApplication1/WebApplication1/132.jpg";
Bitmap bmp = new Bitmap(Imagefilename);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
return Convert.ToBase64String(arr);
}
catch (Exception ex)
{
return ex.ToString();
}
}
注:如果是线上文件需要自己写下载函数把图片下载到本地才可以进行转换