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; } }
只需要传入一个Bitmap对象,亲测可用哈。返回给前台时,将转换成base64的码前面加上
data:image/png;base64,
例如:
Bitmap bt; string base64Img = ImgToBase64String(bt); this.Image1.ImageUrl = "data:image/png;base64," + base64Img;