有时候,想让自己封装的js干净轻巧,不带图片文件什么的,那图片怎么处理呢?带着这个问题,我做了一下试验,发现也不是很难。现在把简单的过程记录下来,以备后用。
<!DOCTYPE HTML> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>test js option base64 picture</title> <script type="text/javascript" src="./Content/jquery-2.2.0.js"></script> <script type="text/javascript"> var icon = 'data:image/gif;base64,R0lGODlhBAABAIABAMLBwfLx8SH5BAEAAAEALAAAAAAEAAEAAAICRF4AOw=='; function main() { return; var img = '<img id="testImg" src="' + icon + '"/>'; $('#canvas').append(img); } </script> </head> <body onload=" main();"> <div id="canvas" style=" 50px; height: 50px; background-position-y:50px;background-position-x:0;" ></div> <hr> <div id="info" onclick="test();">页面载入中,请稍候...</div> <script type="text/javascript"> function test() { $('#canvas').css({ backgroundImage: 'url(' + icon + ')' }); } </script> </body> </html>下面附带c#取图片base64串的方法:
public static string getImageStr(string imgFile) { var stream = File.Open(imgFile, FileMode.Open); byte[] buff = new byte[stream.Length]; stream.Read(buff, 0, (int)stream.Length); stream.Dispose(); return Convert.ToBase64String(buff); }