将一张图片(通过路径选择)转换为base64字符串

162

如何在C#中将用户计算机上的图像路径转换为base64字符串?

例如,我有图像路径(格式如C:/image/1.gif),并希望获得类似于data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..的数据URI,以表示返回的1.gif图像。


如果你要将它们嵌入到CSS中,请考虑配置构建系统,例如Gulp.js,它可以为您处理此任务。 - Konstantin Tarkus
2
你想要路径字符串被编码还是在那个位置给出一个数据URI的图像? - Marcel
12个回答

240

试一下这个

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

9
为什么还要重新保存呢?你可以直接读取文件的字节并将其转换。 - Nyerguds
3
在我的情况下,是因为我想在加载图像后调整其大小。 - pgee70
@Nyerguds 我认为这是因为它需要原始格式,根据image.RawFormat来判断。 - mekb
2
@facepalm42 RawFormat 不是一个图像格式说明符;它是 image 对象的一个属性,用于返回图像从文件中读取时所处的格式,这意味着在这种情况下,它将返回 gif 格式。因此,它不会改变任何东西,除了你现在拥有的是由 .Net 框架重新保存为 gif 的图像字节,而不是实际原始文件的字节。 - Nyerguds
请注意,由于某种原因,.Net无法将其加载为调色板图像的动画gif(尽管在某些类型的png中也会发生这种情况),并且在将所述“高彩色”图像重新保存为调色板格式时,它使用标准的Windows 256色调色板。由于动画gif通常具有优化的调色板,这意味着通过此过程保存的任何动画gif都将其质量严重降低。因此,这种设置绝对不是理想的;最好只读取原始字节,正如KansaiRobot的答案所示。 - Nyerguds
以上示例不兼容 .net core。 - ADM-IT

196

获取图像的字节数组(byte[])表示形式,然后使用Convert.ToBase64String(),例如:

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

将一个base64图片转换为System.Drawing.Image:

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

3
如果你的意思是将base64转换回System.Drawing.Image,你可以使用这样的代码:var img = Image.FromStream(new MemoryStream(Convert.FromBase64String(base64String))); - Arin Ghazarian

43

由于我们大多数人喜欢简短有力的话:

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

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

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

10

这是我为此目的编写的类:

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

8
您可以轻松地传递图像路径以检索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;
            }
        }
    }

希望这能帮到你。

如果输入是gif格式,这可能会出现问题;它会将其重新保存为与_image.RawFormat获取的相同类型,但将数据公开为mime类型image/jpg - Nyerguds

5

这段代码在 DotNet Core 6 上与我良好运行

using (Image image = Image.FromFile(path))
{
    using (MemoryStream m = new MemoryStream())
    {            
        image.Save(m, ImageFormat.Jpeg);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);

        // In my case I didn't find the part "data:image/png;base64,", so I added.
        return $"data:image/png;base64,{base64String}";
    }
}

3

您可以使用Server.Map路径来提供相对路径,然后您可以使用base64转换创建图像,或者只需将base64字符串添加到image src中。

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

string base64ImageRepresentation = Convert.ToBase64String(imageArray);

2
那样会更简单,您只需传递图像,然后传递格式。
private static string ImageToBase64(Image image)
{
    var imageStream = new MemoryStream();
    try
    {           
        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!";
    }
    finally
    {
      imageStream.Dispose;
    }
}

1

根据获得最高票的答案,更新为C# 8。以下内容可以直接使用。在Image之前添加明确的System.Drawing,因为有人可能默认从其他命名空间使用该类。

public static string ImagePathToBase64(string path)
{
    using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
    using MemoryStream m = new MemoryStream();
    image.Save(m, image.RawFormat);
    byte[] imageBytes = m.ToArray();
    tring base64String = Convert.ToBase64String(imageBytes);
    return base64String;
}

1
你可以通过return Convert.ToBase64String(File.ReadAllBytes(path));来替换整个过程。根本不需要涉及System.Drawing - Nyerguds

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接