C# 字节流通过Base64编码转换成图片代码
// 需载入以下的命名空间
// using System.IO;
// using System.Drawing;
// using System.Runtime.Serialization.Formatters.Binary;
protected void Page_Load(object sender, EventArgs e)
{
byte[] buffer = ReadFile(Server.MapPath(@"\sex.txt"));
char[] ch = new ASCIIEncoding().GetChars(buffer);//或者:char[] ch = Encoding.UTF8.GetChars(buffer)
string base64 = ToBase64();
// 转成图片并保存
//ToImage(base64);
System.Drawing.Image img = ToImage(base64);
img.Save(Server.MapPath(@"\imgbase64.jpg"));
}
/// <summary>
/// 获取byte[]
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private byte[] ReadFile(string fileName)
{
FileStream fs = null;
byte[] byt = new byte[0];
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(fs);
read.BaseStream.Seek(0, SeekOrigin.Begin); //将文件指针设置到文件开
byt = read.ReadBytes((int)read.BaseStream.Length);
fs.Close();
return byt;
}
/// <summary>
/// 将图片数据转换为Base64字符串
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private string ToBase64()
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(@"\sex.jpg"));
BinaryFormatter binFormatter = new BinaryFormatter();
MemoryStream memStream = new MemoryStream();
binFormatter.Serialize(memStream, img);
byte[] bytes = memStream.GetBuffer();
string base64 = Convert.ToBase64String(bytes);
memStream.Close();
return base64;
}
/// <summary>
/// 将Base64字符串转换为图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private System.Drawing.Image ToImage(string value)
{
string base64 = value;
byte[] bytes = Convert.FromBase64String(base64);
MemoryStream memStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter();
System.Drawing.Image img = (System.Drawing.Image)binFormatter.Deserialize(memStream);
memStream.Close();
return img;
}