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;