C#中图片转换为Base64编码,Base64编码转换为图片

时间:2022-06-16 03:46:58

#region 图片转为base64编码的字符串
public string ImgToBase64String(string Imagefilename)
{
try
{
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 null;
}
}
#endregion

#region base64编码的字符串转为图片
public void Base64StringToImage(string strbase64)
{

try
{
byte[] arr = Convert.FromBase64String(strbase64);
MemoryStream ms = new MemoryStream(arr);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);


string ls_path = Server.MapPath(@"images\camera\" + ls_imageNameCamera + ".jpg");

img.Save(ls_path, System.Drawing.Imaging.ImageFormat.Jpeg);

//System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
//img.Save("ImgName.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
//img.Save("ImgName.bmp", ImageFormat.Bmp);
//img.Save("ImgName.gif", ImageFormat.Gif);
//img.Save(@"images\ImgName.png", ImageFormat.Png);

Session["ImageNameCamera"] = ls_imageNameCamera;
}
catch (Exception ex)
{