将图像路径转换为base64字符串

时间:2014-01-24 06:11:29

标签: c# image base64

如何在C#中将图像转换为base64字符串?

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

13 个答案:

答案 0 :(得分:148)

试试这个

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;
    }
}

答案 1 :(得分:83)

获取图像的字节数组(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)));

答案 2 :(得分:22)

因为我们大多数人都喜欢oneliners:

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

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

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

答案 3 :(得分:7)

虽然更复杂的答案是可以的,但我发现这要好得多

var base64String= Convert.ToBase64String(File.ReadAllBytes(pathOfPic));

这很简单,您无需重新保存并处理不同的格式

答案 4 :(得分:6)

这是我为此目的写的课程:

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();

答案 5 :(得分:2)

您可以使用Server.Map路径提供相对路径,然后您可以使用base64转换创建图片,也可以只将base64字符串添加到image src

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

string base64ImageRepresentation = Convert.ToBase64String(imageArray);

答案 6 :(得分:2)

您可以轻松地传递图像的路径来检索base64字符串

public static string ImageToBase64(string _imagePath)
    {
        string _base64String = null;

        using (System.Drawing.Image _image = System.Drawing.Image.FromFile(_imagePath))
        {
            using (MemoryStream _mStream = new MemoryStream())
            {
                _image.Save(_mStream, _image.RawFormat);
                byte[] _imageBytes = _mStream.ToArray();
                _base64String = Convert.ToBase64String(_imageBytes);

                return "data:image/jpg;base64," + _base64String;
            }
        }
    }

希望这会有所帮助。

答案 7 :(得分:1)

这样更简单,你传递图像然后传递格式。

private static string ImageToBase64(Image image)
{
    try
    {
        var imageStream = new MemoryStream();
        image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
        imageStream.Position = 0;
        var imageBytes = imageStream.ToArray();
        var ImageBase64 = Convert.ToBase64String(imageBytes);
        return ImageBase64;
    }
    catch (Exception ex)
    {
        return "Error converting image to base64!";
    }
}

答案 8 :(得分:0)

以下代码对我有用:

string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);

答案 9 :(得分:0)

根据投票结果最高的答案,已针对C#8更新。可以直接使用以下内容。在./run-env之前添加了显式#!/usr/bin/env bash for arg in "$@"; do if [ "$arg" = '-d' ] || [ "$arg" = '--detach' ] then docker-compose -f docker-compose.local-environment.yml up --build -V --detach else docker-compose -f docker-compose.local-environment.yml up --build -V --abort-on-container-exit fi done ,因为默认情况下可能正在使用其他命名空间中的该类。

System.Drawing

答案 10 :(得分:0)

对于到达这里的谷歌员工来说,情况正好相反(对此没有 SO 问题/答案)

public static byte[] BytesFromBase64ImageString(string imageData)
{
    var trunc = imageData.Split(',')[1];
    var padded = trunc.PadRight(trunc.Length + (4 - trunc.Length % 4) % 4, '=');
    return Convert.FromBase64String(padded);
}

答案 11 :(得分:-2)

你可以像这样转换它

  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=

答案 12 :(得分:-2)

像这样的东西

 Function imgTo64(ByVal thePath As String) As String
    Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(thePath)
    Dim m As IO.MemoryStream = New IO.MemoryStream()

    img.Save(m, img.RawFormat)
    Dim imageBytes As Byte() = m.ToArray
    img.Dispose()

    Dim str64 = Convert.ToBase64String(imageBytes)
    Return str64
End Function