码迷,mamicode.com
首页 > Windows程序 > 详细

C# 字节流通过Base64编码转换成图片代码

时间:2016-04-13 01:57:53      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

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

C# 字节流通过Base64编码转换成图片代码

标签:

原文地址:http://www.cnblogs.com/cgw200752027/p/5385218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!