如何将 image 转成 base64 字符串?
Posted dotNET跨平台
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将 image 转成 base64 字符串?相关的知识,希望对你有一定的参考价值。
咨询区
vaj90
我的项目中有一个需求,需要将 base64
格式的字符串 data:image/gif;base64,/9j/4AAQSkZJRgABAgEAYABgAAD..
转成 image 格式,请问我该如何实现?
回答区
Patashu:
我写了一个 image 和 base64 相互转换的帮助类,你可以直接拿去用,参考如下代码:
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)";
然后你可以像下面这样使用。
public static void Main(string[] args)
var base64Img = new Base64Image
FileContents = File.ReadAllBytes("Path to image"),
ContentType = "image/png"
;
string base64EncodedImg = base64Img.ToString();
sumith madhushan:
如果是将 图片路径
转为 base64
字符串,可以先将 路径中的图片
转为 byte[] 形式,然后转为 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;
点评区
说到这个图片的 base64 格式,让我想起来前段时间有位朋友将 base64 格式的图片塞到了 sqlserver,导致程序运行一段时间之后内存过大,所以我建议这种需求,小规模的可以用 nginx 单独做图片服务器,大规模的可以用 fastdfs 或者图省事用阿里的 OSS。
以上是关于如何将 image 转成 base64 字符串?的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript 之 FileReader简介以及原生uniapp如何将文件转成base64编码字符串示例