【发布时间】:2011-08-23 15:38:52
【问题描述】:
我目前有一个应用程序,它可以截取演示者桌面的屏幕截图,然后通过自定义协议将其广播给观众。为了使图像传输速度足够快以获得每秒 2 到 3 张图像的帧速率,我需要确保图像大小始终小于 ~ 300 KB。
我将 C# 用于演示者应用程序,它通过以下过程将屏幕截图编码为 JPEG。我担心的是,使用静态压缩设置时图像质量可能会有很大差异。如果我让应用程序捕获我的屏幕,当我有 Visual Studio 全屏时,图像输出将是 ~200 KB,但如果我最小化我的屏幕并显示我的桌面背景,它将是 ~400 KB。
我可以将编码过程放入一个循环中,并不断减小图像大小,直到字节数组的大小小于 300 KB,但这似乎是一个乏味的操作。有没有其他方法可以使用?
提前致谢。
// get the screenshot
System.Drawing.Rectangle totalSize = System.Drawing.Rectangle.Empty;
//foreach (Screen s in Screen.AllScreens)
totalSize = System.Drawing.Rectangle.Union(totalSize, Screen.PrimaryScreen.Bounds);
Bitmap screenShotBitmap = new Bitmap(totalSize.Width, totalSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
screenShotBitmap.SetResolution(96, 96);
Graphics screenShotGraphics = Graphics.FromImage(screenShotBitmap);
screenShotGraphics.CopyFromScreen(totalSize.X, totalSize.Y,
0, 0, totalSize.Size, CopyPixelOperation.SourceCopy);
screenShotGraphics.Dispose();
// image codec information
ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/jpeg");
// encoder settings
System.Drawing.Imaging.Encoder encoderQuality;
System.Drawing.Imaging.Encoder encoderColor;
encoderQuality = System.Drawing.Imaging.Encoder.Quality;
encoderColor = System.Drawing.Imaging.Encoder.ColorDepth;
// compression & quality for JPEG output
Int64 quality = 40L;
// storage for exported JPEG
byte[] screenShotByteArray;
// encoder parameters
EncoderParameter encoderQualityParameter = new EncoderParameter(encoderQuality, quality);
//EncoderParameter encoderColorParameter = new EncoderParameter(encoderColor, 8L);
// encoder parameters table
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = encoderQualityParameter;
//encoderParameters.Param[1] = encoderColorParameter;
// get the code into a memory stream
MemoryStream screenShotMemoryStream = new MemoryStream();
screenShotBitmap.Save(screenShotMemoryStream, imageCodecInfo, encoderParameters);
// convert to a byte array
screenShotByteArray = screenShotMemoryStream.GetBuffer();
// close the memory stream
screenShotMemoryStream.Close();
【问题讨论】:
-
要实现快速更新,您可以做的最好的事情可能就是避免重新传输未更改的区域。请注意,这并非微不足道 - 远非如此。
标签: c# image encoding screenshot jpeg