C#实例代码:
/// <summary>
/// 图片转base64
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
private string ImgToByte(Bitmap bmp)
{
string result;
try
{
//Image bmp = new Bitmap(filename);
MemoryStream memoryStream = new MemoryStream();
bmp.Save(memoryStream, ImageFormat.Jpeg);
byte[] array = new byte[memoryStream.Length];
memoryStream.Position = 0L;
memoryStream.Read(array, 0, (int)memoryStream.Length);
memoryStream.Close();
result = Convert.ToBase64String(array);
}
catch (Exception ex)
{
result = null;
}
return result;
}
/// <summary>
/// base64转图片
/// </summary>
/// <param name="base64string"></param>
/// <returns></returns>
public Bitmap GetImageFromBase64(string base64string)
{
byte[] b = Convert.FromBase64String(base64string);
MemoryStream ms = new MemoryStream(b);
Bitmap bitmap = new Bitmap(ms);
return bitmap;
}
注:
使用birmap类型,需要在引用右键 -> 添加引用 -> 程序集 搜索 system.drawing 添加即可
python实例代码:
import base64
# 将base64转为图片并保存到指定位置
filepath = 'data/image.jpg'
imagedata = base64.b64decode(imgbase64)
file = open(filepath, "wb")
file.write(imagedata)
file.close()
将图片转为base64
with open('data/cs1.jpg', 'rb') as f: # 以二进制读取图片
data = f.read()
encodestr = base64.b64encode(data) # 得到 byte 编码的数据
cs = str(encodestr, 'utf-8')