将图像path转换为base64string

如何将图像转换为C#中的base64string?

例如,我有图像C:/image/1.gif的path,并希望data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..返回。

尝试这个

 using (Image image = Image.FromFile(Path)) { using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); byte[] imageBytes = m.ToArray(); // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); return base64String; } } 

获取图像的字节数组( byte[] )表示,然后使用Convert.ToBase64String() ,st。 喜欢这个:

 byte[] imageArray = System.IO.File.ReadAllBytes(@"image file path"); string base64ImageRepresentation = Convert.ToBase64String(imageArray); 

将base4图像转换回System.Drawing.Image:

 var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String))); 

这是我为此写作的课程:

 public class Base64Image { public static Base64Image Parse(string base64Content) { if (string.IsNullOrEmpty(base64Content)) { throw new ArgumentNullException(nameof(base64Content)); } int indexOfSemiColon = base64Content.IndexOf(";", StringComparison.OrdinalIgnoreCase); string dataLabel = base64Content.Substring(0, indexOfSemiColon); string contentType = dataLabel.Split(':').Last(); var startIndex = base64Content.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7; var fileContents = base64Content.Substring(startIndex); var bytes = Convert.FromBase64String(fileContents); return new Base64Image { ContentType = contentType, FileContents = bytes }; } public string ContentType { get; set; } public byte[] FileContents { get; set; } public override string ToString() { return $"data:{ContentType};base64,{Convert.ToBase64String(FileContents)}"; } } var base64Img = new Base64Image { FileContents = File.ReadAllBytes("Path to image"), ContentType="image/png" }; string base64EncodedImg = base64Img.ToString(); 

由于我们大多数人喜欢线索:

 Convert.ToBase64String(File.ReadAllBytes(imageFilepath)); 

如果你需要它作为Base64字节数组:

 Encoding.ASCII.GetBytes(Convert.ToBase64String(File.ReadAllBytes(imageFilepath))); 

您可以使用Server.Mappath给出相对path,然后您可以使用base64转换创build图像,或者您可以将base64string添加到image src

 byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png")); string base64ImageRepresentation = Convert.ToBase64String(imageArray); 

你可以像这样转换它

  string test = @"C:/image/1.gif"; byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(test); string base64String = System.Convert.ToBase64String(bytes); Console.WriteLine("Base 64 string: " + base64String); 

产量

  QzovaW1hZ2UvMS5naWY=