1. 程式人生 > >C#獲取微信二維碼顯示到wpf

C#獲取微信二維碼顯示到wpf

微信的api開放的二維碼是一個連結地址,而我們要將這個二維碼顯示到客戶端。方式很多,今天我們講其中一種。

 /// <summary>
        /// 獲取圖片路徑
        /// </summary>
        /// <param name="httpUrl"></param>
        /// <returns></returns>
        public string GetImageUrl(string httpUrl)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(httpUrl);
            req.ServicePoint.Expect100Continue 
= false; req.Method = "GET"; req.KeepAlive = true; req.ContentType = "image/png"; HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(rsp.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string str = reader.ReadToEnd(); string[] imgStr = GetHtmlImageUrlList(str); string strer = "https://open.weixin.qq.com" + imgStr[0]; return strer; } /// <summary> /// 獲取img標籤 /// </summary> /// <param name="sHtmlText"></param>
/// <returns></returns> public string[] GetHtmlImageUrlList(string sHtmlText) { Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); MatchCollection matches = regImg.Matches(sHtmlText); int i = 0; string[] sUrlList = new string[matches.Count]; foreach (Match match in matches) sUrlList[i++] = match.Groups["imgUrl"].Value; return sUrlList; }

呼叫方式:

string imgUrl= GetImageUrl("https://open.weixin.qq.com/......微信地址");
            img.Source = new BitmapImage(new Uri(imgUrl));

這個是訪問微信地址url,獲取到這個url中顯示的微信二維碼,拿到這個圖片,顯示到wpf

更多方式瞭解請加頁面下方的群