微信公共服务平台开发(.Net 的实现)8-------处理图片(上传下载发送)



举个例子,有人对着我们的公共微信号拍个照片发送过来,然后我们处理这个照片,比如进行ocr识别字(随后就会降到这个例子),或者人脸识别,或者拍照取证等,这些功能都是相当有用的。那么我们现在就要分析一下这个过程。微信平台肯定不能帮助我们OCR或者人脸识别等功能,要做这些功能首先到得到图片!用户拍摄的照片首先被上传到了wenxin的服务器,然后就有了一个mediaID,我们用这个mediaID可以下载到我们自己的服务器上然后处理,把结果给微信平台,由微信平台最终反馈给用户(关注者)。微信的开发文档已经给出了下载资源的办法,我改造为.net的,如下:

[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /// <summary>  
  2.     /// 下载保存多媒体文件,返回多媒体保存路径  
  3.     /// </summary>  
  4.     /// <param name="ACCESS_TOKEN"></param>  
  5.     /// <param name="MEDIA_ID"></param>  
  6.     /// <returns></returns>  
  7.     public string GetMultimedia(string ACCESS_TOKEN, string MEDIA_ID)  
  8.     {  
  9.         string file = string.Empty;  
  10.         string content = string.Empty;  
  11.         string strpath = string.Empty;  
  12.         string savepath = string.Empty;  
  13.         string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + ACCESS_TOKEN + "&media_id=" + MEDIA_ID;  
  14.   
  15.         HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);  
  16.   
  17.         req.Method = "GET";  
  18.         using (WebResponse wr = req.GetResponse())  
  19.         {  
  20.             HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();  
  21.   
  22.             strpath = myResponse.ResponseUri.ToString();  
  23.             WriteLog("接收类别://" + myResponse.ContentType);  
  24.             WebClient mywebclient = new WebClient();  
  25.             savepath = Server.MapPath("image") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + ".jpg";  
  26.             WriteLog("路径://" + savepath);  
  27.             try  
  28.             {  
  29.                 mywebclient.DownloadFile(strpath, savepath);  
  30.                 file = savepath;  
  31.             }  
  32.             catch (Exception ex)  
  33.             {  
  34.                 savepath = ex.ToString();  
  35.             }  
  36.   
  37.         }  
  38.         return file;  
  39.     }  

上面的两个参数很好理解,第一就是ACCESS_TOKEN,之前说过很多了,第二就是在微信服务器上的资源id,即mediaID。如果我们要下载微信服务器上的资源总要知道id吧。但是MEDIA_ID又是怎么产生的呢?我首先改造一下之前的消息实体类,加入MediaId 属性
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class wxmessage    
  2.   {    
  3.       public string FromUserName { getset; }    
  4.       public string ToUserName { getset; }    
  5.        public string MsgType { getset; }    
  6.        public string EventName { getset; }    
  7.        public string Content { getset; }  
  8.        public string Recognition { getset; }  
  9.        public string MediaId { getset; }  
  10.        public string EventKey { getset; }   
  11.    }  
然后改造一下GetWxMessage(),给MediaId赋值。
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private wxmessage GetWxMessage()  
  2.      {  
  3.          wxmessage wx = new wxmessage();  
  4.          StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);  
  5.          XmlDocument xml = new XmlDocument();  
  6.          xml.Load(str);  
  7.          wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;  
  8.          wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;  
  9.          wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;  
  10.          if (wx.MsgType.Trim() == "text")  
  11.          {  
  12.              wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;  
  13.          }  
  14.          if (wx.MsgType.Trim() == "event")  
  15.          {  
  16.              wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;  
  17.              wx.EventKey = xml.SelectSingleNode("xml").SelectSingleNode("EventKey").InnerText;  
  18.          }  
  19.          if (wx.MsgType.Trim() == "voice")  
  20.          {  
  21.              wx.Recognition = xml.SelectSingleNode("xml").SelectSingleNode("Recognition").InnerText;  
  22.          }  
  23.         if (wx.MsgType.Trim() == "image")  
  24.         {  
  25.             wx.MediaId = xml.SelectSingleNode("xml").SelectSingleNode("MediaId").InnerText;  
  26.         }  
  27.            
  28.          return wx;  
  29.      }  
如果我们在修改一下消息接受的代码,就可以做到,客户发一个照片给微信平台,程序检测到时图片,然后根据MediaId,调用GetMultimedia方法把图片下载到自己的服务器上。后面的工作嘛,你就想干什么干什么了。
刚才的例子好像是用户(关注者),发图片,然后通过微信平台到我们的服务器中,还有一种情况,用户发一个用户名:例如“hemeng”,然后我需要调用已经存在服务器中的hemeng头像的图片反馈给用户,这怎么办呢?如何把我们的图片传给微信平台,然后传给用户呢?我们就用到了上传得方法:
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /// <summary>  
  2.     /// 上传多媒体文件,返回 MediaId  
  3.     /// </summary>  
  4.     /// <param name="ACCESS_TOKEN"></param>  
  5.     /// <param name="Type"></param>  
  6.     /// <returns></returns>  
  7.     public string UploadMultimedia(string ACCESS_TOKEN, string Type)  
  8.     {  
  9.         string result = "";  
  10.         string wxurl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + ACCESS_TOKEN + "&type=" + Type;  
  11.         string filepath = Server.MapPath("image") + "\\hemeng80.jpg";(本地服务器的地址)  
  12.         WriteLog("上传路径:" + filepath);  
  13.         WebClient myWebClient = new WebClient();  
  14.         myWebClient.Credentials = CredentialCache.DefaultCredentials;  
  15.         try  
  16.         {  
  17.             byte[] responseArray = myWebClient.UploadFile(wxurl, "POST", filepath);  
  18.             result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);  
  19.             WriteLog("上传result:" + result);  
  20.             UploadMM _mode = JsonHelper.ParseFromJson<UploadMM>(result);  
  21.             result = _mode.media_id;  
  22.         }  
  23.         catch (Exception ex)  
  24.         {  
  25.             result = "Error:" + ex.Message;  
  26.         }  
  27.         WriteLog("上传MediaId:" + result);  
  28.         return result;  
  29.     }  
第二个参数如果是图片"image",可以参照微信的文档。函数的返回值就是一个MediaId,这样你就可以利用发送图片的函数,发给客户了,发送图片的函数如下:
[csharp] view plain copy 在CODE上查看代码片 派生到我的代码片
  1. protected string sendPicTextMessage(Msg _mode, string MediaId)  
  2.     {  
  3.         string res = string.Format(@"<xml>  
  4.                                             <ToUserName><![CDATA[{0}]]></ToUserName>  
  5.                                             <FromUserName><![CDATA[{1}]]></FromUserName>  
  6.                                             <CreateTime>{2}</CreateTime>  
  7.                                             <MsgType><![CDATA[image]]></MsgType>  
  8.                                             <Image>  
  9.                                             <MediaId><![CDATA[{3}]]></MediaId>  
  10.                                             </Image>  
  11.                                    </xml> ",  
  12.            _mode.FromUserName, _mode.ToUserName, DateTime.Now, MediaId);  
  13.   
  14.         return res;  
  15.     }  
其他视频,语音的操作也类似,就不再冗余介绍了。有了这些知识我们是不是能做不少应用了?当然是肯定的,但是我们的代码还不够优化,结构也不合理,不着急,我们会逐渐介绍到的,因为我们还没有完全了解完微信的强大功能。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值