C# - 如何使用 Jpeg 压缩图像并发送到服务器?
我想用 C# 构建一个屏幕共享程序。(使用 TCP)
我在网上嗅了一下,发现最有效的方法是从客户端向服务器发送大量屏幕截图。
重点是 - 如何将位图压缩为 Jpeg - 在服务器上接收它并再次解压缩为位图(以便我可以以表单形式显示它)?
我尝试使用 JpegBitmapEncoder 但没有成功,这是我的代码:
Bitmap screen = TakeScreenshot();
MemoryStream ms = new MemoryStream();
byte[] Bytes = BmpToBytes_Unsafe(screen);
ms.Write(Bytes, 0, Bytes.Length);
Jpeg = new JpegBitmapEncoder();
Jpeg.Frames.Add(BitmapFrame.Create(ms));
Jpeg.QualityLevel = 40;
Jpeg.Save(ms);
BinaryReader br = new BinaryReader(ms);
SendMessage(br.ReadBytes((int)ms.Length));
它在 Jpeg.Frames.Add(BitmapFrame.Create(ms));
处抛出 NotSupportedException 找不到适合完成此操作的成像组件。
所以我需要一种方法将位图转换为 Jpeg,然后转换为 byte[],然后通过 TCP 发送。
在另一端,做完全相反的事情。有什么建议吗?
谢谢。
I want to build a Screen Sharing program in C#.(with TCP)
I sniffed around the web and found out that the most efficient way to do it is by sending alot of screenshots from the client to the server.
The point is - how can I compress a Bitmap to Jpeg - receive it on the server and decompress again to Bitmap (so I can show it in a form) ?
I've tried using the JpegBitmapEncoder with no luck, here's my code:
Bitmap screen = TakeScreenshot();
MemoryStream ms = new MemoryStream();
byte[] Bytes = BmpToBytes_Unsafe(screen);
ms.Write(Bytes, 0, Bytes.Length);
Jpeg = new JpegBitmapEncoder();
Jpeg.Frames.Add(BitmapFrame.Create(ms));
Jpeg.QualityLevel = 40;
Jpeg.Save(ms);
BinaryReader br = new BinaryReader(ms);
SendMessage(br.ReadBytes((int)ms.Length));
It throws an NotSupportedException at Jpeg.Frames.Add(BitmapFrame.Create(ms));
No imaging component suitable to complete this operation was found.
So I need a way to convert a Bitmap to Jpeg, then to byte[], then send it over TCP.
And on the other end, do the exact opposite. Any suggestions ?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JPEG 是为照片而不是屏幕截图而设计的。此外,大部分屏幕不会发生变化,因此最好只发送更改的部分,并且当大部分屏幕发生变化时仅发送全屏。
除非你这样做只是为了好玩,否则你的做法就大错特错了。 VNC 多年来一直在这样做,并且源代码是免费的,因此您可以查看它是如何完成的。
JPEG was designed for photographs, not for screen captures. Also, most of the screen doesn't change so better to just send the changed portions and only a full screen when much of the screen has changed.
Unless you're just doing this for fun, you are going about this all wrong. VNC has been doing this for years and the source code is free so you could look to see how that's done.