小编给大家分享一下微信小程序如何获取小程序码并接受buffer流保存为图片,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
操作
因为我获取到了微信那里的图片的图片流一直不知道怎么处理,今天总算找到相关文档,解决了。因为数据流不能直接传给前端,只好把buffer流转成图片保存在服务器上,没办法啊~
废话不多说上代码
public static string Api_Post(string postUrl, string postData, WebHeaderCollection header = null,bool isPic=false) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(postUrl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (header != null) request.Headers = header; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); if (isPic) { byte[] tt = StreamToBytes(instream);//将数据流转为byte[] System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/WxCode.jpg"), tt); WxQRCodeModel model = new WxQRCodeModel(); model.data = "192.168.1.216:80/WxCode.jpg"; model.errcode = 0; string content = Config.js.Serialize(model); string err = string.Empty; return content; } else { sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } } catch (Exception ex) { if (isPic) { sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } else { string err = ex.Message; return string.Empty; } } }
因为是instream接受到微信接口那里发送过来的数据流,就在instream那里处理,把数据流转换为byte[]数组,然后依靠File的WriteAllBytes方法把转换OK的byte[]数组转换为图片存放在服务器上,然后把图片路径交给model。
///将数据流转为byte[] public static byte[] StreamToBytes(Stream stream) { List<byte> bytes = new List<byte>(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } return bytes.ToArray(); }
以上是“微信小程序如何获取小程序码并接受buffer流保存为图片”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。