【问题标题】:Get Binary Data From Client and Save it as image从客户端获取二进制数据并将其保存为图像
【发布时间】:2014-03-16 04:04:34
【问题描述】:

我创建了本地服务器,它应该获取图像文件作为二进制数据并将它们作为图像保存在硬盘中。

Socket mySocket = myListener.AcceptSocket();

#region Connection Check
if (mySocket.Connected)
{
        ============
    /* Some Code For Displaying Information*/
        ============

    byte[] data = new byte[mySocket.ReceiveBufferSize];
    int i = mySocket.Receive(data, data.Length, 0);

    byteArrayToImage(data); 

    mySocket.Close();
}

byteArrayToImage 方法将字节数组转换为图像文件并保存在硬盘上,这是代码

public void byteArrayToImage(Byte[] data)
{
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    img.Save(@"C:\MyPersonalwebServer\ImageData\img.png", ImageFormat.Png);
}

但我在这里得到 ArgumentException:Image img = Image.FromStream(ms)

这里是data array的一部分:http://s43.radikal.ru/i101/1403/78/1913ab884790.png

任何想法如何解决它? 提前致谢。

【问题讨论】:

  • 堆栈跟踪说明了什么?
  • 异常信息是什么?
  • 您的缓冲区大小不太可能包含完整的图像。
  • @MrDustpan 堆栈跟踪是什么?
  • @SLaks System.Drawing.dll 中出现“System.ArgumentException”类型的未处理异常附加信息:参数无效。

标签: c# bytearray localserver


【解决方案1】:

以下代码适用于我:

var buffer = new byte[256];
FileStream fs = new FileStream(@"D:\test.png", FileMode.Open);
var ms = new MemoryStream();

int readCtr;
while ((readCtr = fs.Read(buffer, 0, buffer.Length)) > 0) 
{
    ms.Write(buffer, 0, readCtr);
}
Image img = Image.FromStream(ms);
img.Save(@"D:\test2.png", ImageFormat.Png);

您确定从客户端连接发送的数据是完整/干净的吗?

确保您在执行 Socket.Send() 时从客户端发送的数据没有附加空字节,或者尝试通过从字节数组末尾剥离任何空字节来清理服务器端:

buffer = buffer.Where(x => x != (byte)0).ToArray();

您还可以使用标准调试实践/控制台输出手动检查图像大小与服务器端接收的内容。

无论哪种方式,如果字节数组具有有效内容,我认为您的代码不会失败。

【讨论】:

  • 数据来自 Flash 应用程序。首先,我们测试了在二进制转换后的字符串数据上的代码,它运行良好。
  • 我还检查了接收和发送的数据大小,它们是相同的。
  • 好的。我唯一可以重新创建您得到的异常是如果我的字节数组不正确...如果您确定从套接字连接检索到的数据正是图像的数据被发送那么它必须与您读取数组的方式有关。字节数组的最大大小是 'Int32.MaxValue' ...您要检索的图像是否比这更大?
  • 我会重新检查图像是否在Flash应用程序中正确转换为二进制并尽快回复。
猜你喜欢
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多