首页 > 编程 > C# > 正文

C#远程发送和接收数据流生成图片的方法

2019-10-29 21:40:11
字体:
来源:转载
供稿:网友

这篇文章主要介绍了C#远程发送和接收数据流生成图片的方法,涉及C#通过数据流传输图片的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#远程发送和接收数据流生成图片的方法。分享给大家供大家参考。具体如下:

将图片转成数据流方式发送到远程服务,在通过服务器后台程序来接收数据流,再保存成图片存放在需要的地方。

这种方式就类似上传图片功能一样,希望能给一些大家另一种上传图片功能的方法。

发送数据流方法

 

 
  1. /// <summary> 
  2. /// PostBinaryData 
  3. /// </summary> 
  4. /// <param name="url">要发送的 url 网址</param> 
  5. /// <param name="bytes">要发送的数据流</param> 
  6. /// <returns></returns> 
  7. public string PostBinaryData(string url, byte[] bytes) 
  8. //下面是测试例子 
  9. //string url = "http://www.test.com/test.ashx"; 
  10. //string img = HttpContext.Current.Server.MapPath("../images/test.jpg"); 
  11. //byte[] bytes = File.ReadAllBytes(img); 
  12. HttpWebRequest wRequest = (HttpWebRequest)WebRequest.Create(url); 
  13. wRequest.ContentType = "multipart/form-data"
  14. wRequest.ContentLength = bytes.Length; 
  15. wRequest.Method = "POST"
  16. Stream stream = wRequest.GetRequestStream(); 
  17. stream.Write(bytes, 0, bytes.Length); 
  18. stream.Close(); 
  19. HttpWebResponse wResponse = (HttpWebResponse)wRequest.GetResponse(); 
  20. StreamReader sReader = new StreamReader(wResponse.GetResponseStream(), System.Text.Encoding.UTF8); 
  21. string str = sReader.ReadToEnd(); 
  22. sReader.Close(); 
  23. wResponse.Close(); 
  24. return str; 

接收数据流方法

 

 
  1. public void GetBinaryData() 
  2. string imgFile = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg"
  3. string filePath = HttpContext.Current.Server.MapPath(imgFile); 
  4. //方法一 
  5. int lang = HttpContext.Current.Request.TotalBytes; 
  6. byte[] bytes = HttpContext.Current.Request.BinaryRead(lang); 
  7. string content = System.Text.Encoding.UTF8.GetString(bytes); 
  8. FileStream fStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); 
  9. BinaryWriter bw = new BinaryWriter(fStream); 
  10. bw.Write(bytes); 
  11. bw.Close(); 
  12. fStream.Close();  
  13. //方法二 
  14. Bitmap img = new Bitmap(HttpContext.Current.Request.InputStream); 
  15. img.Save(filePath); 
  16. HttpContext.Current.Response.Write("ok"); 

希望本文所述对大家的C#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表