[.NET]Base 64圖片與Image物件互轉
挺好用的,做個筆記紀錄一下
base 64圖片字串轉Image物件:
/// <summary>
/// base 64字串格式的圖片轉成Image物件
/// </summary>
/// <param name="base64String"></param>
/// <returns></returns>
public static Image Base64StringToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] Buffer = Convert.FromBase64String(base64String);
byte[] data = null;
Image oImage = null;
MemoryStream oMemoryStream = null;
Bitmap oBitmap = null;
//建立副本
data = (byte[])Buffer.Clone();
try
{
oMemoryStream = new MemoryStream(data);
//設定資料流位置
oMemoryStream.Position = 0;
oImage = System.Drawing.Image.FromStream(oMemoryStream);
//建立副本
oBitmap = new Bitmap(oImage);
}
catch
{
throw;
}
finally
{
oMemoryStream.Close();
oMemoryStream.Dispose();
oMemoryStream = null;
}
//return oImage;
return oBitmap;
}
Image物件轉base 64的圖片
public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to base 64 string
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
參考資料:
C# Base64 String to JPEG Image
https://stackoverflow.com/questions/18827081/c-sharp-base64-string-to-jpeg-image/18827264#18827264