public static class BitmapOper
{
//图片转为base64编码的字符串
public static string ImgToBase64String(Bitmap bmp)
{
try
{
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 null;
}
}
//threeebase64编码的字符串转为图片
public static Bitmap Base64StringToImage(string strbase64)
{
try
{
byte[] arr = Convert.FromBase64String(strbase64);
MemoryStream ms = new MemoryStream(arr);
Bitmap bmp = new Bitmap(ms);
ms.Close();
return bmp;
}
catch (Exception ex)
{
return null;
}
}
}
用法
//项目根目录
string path = Server.MapPath("~/");
string imgpath = path + "\\img\\IMG_4796.JPG";
//根据路径获取图片对象
Bitmap bmp = (Bitmap)Image.FromFile(imgpath);
//调用方法转为base64
string base64 = BitmapOper.ImgToBase64String(bmp);
//调用方法将base64转为Image对象
Image img = BitmapOper.Base64StringToImage(base64);