C#远程发送和接收数据流生成图片的方法
本文实例讲述了C#远程发送和接收数据流生成图片的方法。分享给大家供大家参考。具体如下:
将图片转成数据流方式发送到远程服务,在通过服务器后台程序来接收数据流,再保存成图片存放在需要的地方。
这种方式就类似上传图片功能一样,希望能给一些大家另一种上传图片功能的方法。
发送数据流方法
///<summary>
///PostBinaryData
///</summary>
///<paramname="url">要发送的url网址</param>
///<paramname="bytes">要发送的数据流</param>
///<returns></returns>
publicstringPostBinaryData(stringurl,byte[]bytes)
{
//下面是测试例子
//stringurl="http://www.test.com/test.ashx";
//stringimg=HttpContext.Current.Server.MapPath("../images/test.jpg");
//byte[]bytes=File.ReadAllBytes(img);
HttpWebRequestwRequest=(HttpWebRequest)WebRequest.Create(url);
wRequest.ContentType="multipart/form-data";
wRequest.ContentLength=bytes.Length;
wRequest.Method="POST";
Streamstream=wRequest.GetRequestStream();
stream.Write(bytes,0,bytes.Length);
stream.Close();
HttpWebResponsewResponse=(HttpWebResponse)wRequest.GetResponse();
StreamReadersReader=newStreamReader(wResponse.GetResponseStream(),System.Text.Encoding.UTF8);
stringstr=sReader.ReadToEnd();
sReader.Close();
wResponse.Close();
returnstr;
}
接收数据流方法
publicvoidGetBinaryData()
{
stringimgFile=DateTime.Now.ToString("yyyyMMddhhmmss")+".jpg";
stringfilePath=HttpContext.Current.Server.MapPath(imgFile);
//方法一
intlang=HttpContext.Current.Request.TotalBytes;
byte[]bytes=HttpContext.Current.Request.BinaryRead(lang);
stringcontent=System.Text.Encoding.UTF8.GetString(bytes);
FileStreamfStream=newFileStream(filePath,FileMode.Create,FileAccess.Write);
BinaryWriterbw=newBinaryWriter(fStream);
bw.Write(bytes);
bw.Close();
fStream.Close();
//方法二
Bitmapimg=newBitmap(HttpContext.Current.Request.InputStream);
img.Save(filePath);
HttpContext.Current.Response.Write("ok");
}
希望本文所述对大家的C#程序设计有所帮助。