C#和Python 圖片和base64的互轉

C#實例代碼:python

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

 

 

注:orm

使用birmap類型,須要在引用右鍵 -> 添加引用 -> 程序集 搜索 system.drawing 添加便可圖片

 

python實例代碼:utf-8

import base64
# 將base64轉爲圖片並保存到指定位置
filepath = 'data/image.jpg'
imagedata = base64.b64decode(imgbase64)
file = open(filepath, "wb")
file.write(imagedata)
file.close()

將圖片轉爲base64string

with open('data/cs1.jpg', 'rb') as f:  # 以二進制讀取圖片    data = f.read()    encodestr = base64.b64encode(data)  # 獲得 byte 編碼的數據    cs = str(encodestr, 'utf-8')
相關文章
相關標籤/搜索