一、字符串转Base64编码相互转化
(1)字符串=》Base64
public static string EncodeBase64(string code_type, string code)
{
string encode = "";
byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
try
{
encode = Convert.ToBase64String(bytes);
}
catch
{
encode = code;
}
return encode;
}
调用方法:
var val1 = EncodeBase64(“utf-8”, “你好啊”);
(2)Base64转字符串
public static string DecodeBase64(string code_type, string code)
{
string decode = "";
byte[] bytes = Convert.FromBase64String(code);
try
{
decode = Encoding.GetEncoding(code_type).GetString(bytes);
}
catch
{
decode = code;
}
return decode;
}
调用方法:
var val2 = DecodeBase64(“utf-8”, “PHRyPjx0ZD7kvaDlpb3llYo8L3RkPjwvdHI+”);
二、图片对象与Base64的相互转换
(1)图片转为base64编码的字符串
#region 图片转为base64编码的字符串
public string ImgToBase64String(string Imagefilename)
{
try
{
Bitmap bmp = new Bitmap(Imagefilename);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
return Convert.ToBase64String(arr);
}
catch (Exception ex)
{
return null;
}
}
#endregion
(2)base64编码的字符串转为图片
#region base64编码的字符串转为图片
public void Base64StringToImage(string strbase64)
{
try
{
byte[] arr = Convert.FromBase64String(strbase64);
MemoryStream ms = new MemoryStream(arr);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
string ls_path = Server.MapPath(@"images\camera\" + ls_imageNameCamera + ".jpg");
img.Save(ls_path, System.Drawing.Imaging.ImageFormat.Jpeg);
//System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
//img.Save("ImgName.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
//img.Save("ImgName.bmp", ImageFormat.Bmp);
//img.Save("ImgName.gif", ImageFormat.Gif);
//img.Save(@"images\ImgName.png", ImageFormat.Png);
Session["ImageNameCamera"] = ls_imageNameCamera;
}
catch (Exception ex)
{
}
}
#endregion
三、文件与base64相互转换(文件为任意格式)
(1)文件转base64字符串,文件可以为任意格式,代码如下:
/// <summary>
/// 文件转base64
/// </summary>
/// <returns>base64字符串</returns>
public string FileToBase64String(string File)
{
FileStream fsForRead = new FileStream(File, FileMode.Open);//文件路径
string base64Str = "";
try
{
//读写指针移到距开头10个字节处
fsForRead.Seek(0, SeekOrigin.Begin);
byte[] bs = new byte[fsForRead.Length];
int log = Convert.ToInt32(fsForRead.Length);
//从文件中读取10个字节放到数组bs中
fsForRead.Read(bs, 0, log);
base64Str = Convert.ToBase64String(bs);
return base64Str;
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.ReadLine();
return base64Str;
}
finally
{
fsForRead.Close();
}
}
(2)base64字符串转文件,文件可以为任意格式,代码如下:
/// <summary>
/// Base64字符串转文件并保存
/// </summary>
/// <param name="base64String">base64字符串</param>
/// <param name="fileName">保存的文件名</param>
/// <returns>是否转换并保存成功</returns>
public bool Base64StringToFile(string base64String, string fileName)
{
bool opResult = false;
try
{
string strDate = DateTime.Now.ToString("yyyyMMdd");
string fileFullPath = "C:\\WGQ_GROUP_DSMS.SysAdmin\\UpFile\\" + strDate;//文件保存路径
if (!Directory.Exists(fileFullPath))
{
Directory.CreateDirectory(fileFullPath);
}
string strbase64 = base64String.Trim().Substring(base64String.IndexOf(",") + 1); //将‘,’以前的多余字符串删除
MemoryStream stream = new MemoryStream(Convert.FromBase64String(strbase64));
FileStream fs = new FileStream(fileFullPath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.Write);
byte[] b = stream.ToArray();
fs.Write(b, 0, b.Length);
fs.Close();
opResult = true;
}
catch (Exception e)
{
logger.Error("异常类型: \t" + e.GetType());
logger.Error("异常描述:\t" + e.Message);
logger.Error("异常方法:\t" + e.TargetSite);
logger.Error("异常堆栈:\t" + e.StackTrace);
}
return opResult;
}