您好,登錄后才能下訂單哦!
小編給大家分享一下微信小程序如何獲取小程序碼并接受buffer流保存為圖片,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
操作
因?yàn)槲耀@取到了微信那里的圖片的圖片流一直不知道怎么處理,今天總算找到相關(guān)文檔,解決了。因?yàn)閿?shù)據(jù)流不能直接傳給前端,只好把buffer流轉(zhuǎn)成圖片保存在服務(wù)器上,沒(méi)辦法啊~
廢話不多說(shuō)上代碼
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); // 準(zhǔn)備請(qǐng)求... try { // 設(shè)置參數(shù) 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(); //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開(kāi)始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求 instream = response.GetResponseStream(); if (isPic) { byte[] tt = StreamToBytes(instream);//將數(shù)據(jù)流轉(zhuǎn)為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); //返回結(jié)果網(wǎng)頁(yè)(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } } catch (Exception ex) { if (isPic) { sr = new StreamReader(instream, encoding); //返回結(jié)果網(wǎng)頁(yè)(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } else { string err = ex.Message; return string.Empty; } } }
因?yàn)槭莍nstream接受到微信接口那里發(fā)送過(guò)來(lái)的數(shù)據(jù)流,就在instream那里處理,把數(shù)據(jù)流轉(zhuǎn)換為byte[]數(shù)組,然后依靠File的WriteAllBytes方法把轉(zhuǎn)換OK的byte[]數(shù)組轉(zhuǎn)換為圖片存放在服務(wù)器上,然后把圖片路徑交給model。
///將數(shù)據(jù)流轉(zhuǎn)為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流保存為圖片”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。