gpt4 book ai didi

C# 通过 HTTP 发送图像

转载 作者:可可西里 更新时间:2023-11-01 07:47:58 26 4
gpt4 key购买 nike

我这里有一个用 C# 编写的小型 HTTP 服务器,直到现在我只需要将原始文本发送回发件人。但现在我必须发送 JPG 图像,但我不知道如何发送。

这是我现在拥有的:

// Read the HTTP Request
Byte[] bReceive = new Byte[MAXBUFFERSIZE];
int i = socket.Receive(bReceive, bReceive.Length, 0);

//Convert Byte to String
string sBuffer = Encoding.ASCII.GetString(bReceive);

// Look for HTTP request
iStartPos = sBuffer.IndexOf("HTTP", 1);

// Extract the Command without GET_/ at the beginning and _HTTP at the end
sRequest = sBuffer.Substring(5, iStartPos - 1 - 5);
String answer = handleRequest(sRequest);


// Send the response
socket.Send(Encoding.UTF8.GetBytes(answer));

我想我必须做某种文件流而不是字符串,但我真的没有胶水..

最佳答案

您要从文件还是位图对象发送?

MemoryStream myMemoryStream = new MemoryStream();
myImage.Save(myMemoryStream);
myMemoryStream.Position = 0;

编辑

// Send the response
SendVarData(socket,memoryStream.ToArray());

要通过套接字发送 MemoryStream,您可以使用给出的方法 here

 private static int SendVarData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;

byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);

while (total < size)
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}

关于C# 通过 HTTP 发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com