=波波日志 > Asp.Net/C#/WCF > Asp.Net图片base64编码相互转换=

Asp.Net图片base64编码相互转换

  如果能将图片转换为base64编码,结合图片的新写法data:images/gif;base64,base64数据,就能使用ajax请求动态页获取base64编码,然后设置img为base64编码即可实现ajax无刷新获取图片信息了。

  一般意义上是不需要使用ajax来获取图片信息的,用JavaScript设置img标签的src属性即可实现无刷新获取到图片,只是浏览器会出现进度条而已。如果要想使用ajax来无刷新获取图片信息,并且更新img标签,就需要动态页将图片编码为base64返回,然后ajax获取返回的信息设置img的src为data:images/gif;base64,base64数据即可。

  下面为asp.net-C#图片-base64编码互转源代码

+展开
-C#

//代码来源于:http://blog.csdn.net/marquess/archive/2008/07/29/2732629.aspx
//图片转为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;
}
}

//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/C#/WCF 作者:波波 日期:2011-02-14 【评论:0】 
 
暂时没有评论!
发表留言
  • *昵称:
  • 头像:
  • 电子邮件: [留下您的邮件,方便管理员回复您。]
  • 个人网站: *验证码:
声明:本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载或引用的作品侵犯了您的权利,请通知我们,我们会及时删除!
Powered by showbo,©2012,桂ICP备05005887号 京公网安备1101055090