Asp.Net把图片转换成base64代码 net把base64代码转换成图片
如果能将图片转换为base64编码,结合图片的新写法data:images/gif;base64,base64数据,就能使用ajax请求动态页获取base64编码,然后设置img为base64编码即可实现ajax无刷新获取图片信息了
//Asp.Net把图片转为base64编码的字符串
protected 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;
}
}
//Asp.Net把base64编码的字符串转为图片
protected Bitmap Base64StringToImage(string strbase64)
{
try
{
byte[] arr = Convert.FromBase64String(strbase64);
MemoryStream ms = new MemoryStream(arr);
Bitmap bmp = new Bitmap(ms);
//bmp.Save("test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
//bmp.Save("test.bmp", ImageFormat.Bmp);
//bmp.Save("test.gif", ImageFormat.Gif);
//bmp.Save("test.png", ImageFormat.Png);
ms.Close();
return bmp;
}
catch (Exception ex)
{
return null;
}
}
asp.net也可以用BinaryWriter生成图片,增加判断是否空的方法
/// <summary>
/// base64编码的字符串转为图片
/// </summary>
/// <param name="filefullname">图片的完整路径 png文件</param>
/// <param name="strbase64">base64格式的图片</param>
/// <returns></returns>
public static bool Base64StringToImage(string filefullname, string strbase64)
{
if (strbase64.IsEmpty())
return false;
byte[] arr = Convert.FromBase64String(strbase64);
if (arr == null || arr.Length <= 0)
return false;
MemoryStream ms = new MemoryStream(arr);
if (ms == null || ms.Length <= 0)
return false;
Bitmap bmp = new Bitmap(ms);
try
{
bmp.Save(filefullname, System.Drawing.Imaging.ImageFormat.Png);
return true;
}
catch (Exception ex)
{
LogHelper.LogWrite(ex);
return false;
}
finally {
ms?.Close();
bmp?.Dispose();
}
}
补充:云计算 , 云安全