所以..我正在创建一个简单的桌面查看器应用程序。
但是当我尝试通过流反序列化已发送的图像时,我一直收到这个System.outOfMmemoryException。
发送代码:
private Image getScreen() {
Rectangle bound = Screen.PrimaryScreen.Bounds;
Bitmap ScreenShot = new Bitmap(bound.Width,bound.Height,PixelFormat.Format32bppArgb );
Graphics image = Graphics.FromImage(ScreenShot);
image.CopyFromScreen(bound.X,bound.Y,0,0,bound.Size,CopyPixelOperation.SourceCopy);
return ScreenShot;
}
private void SendImage() {
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(stream, getScreen());
}
请注意,图像是使用定时器发送的,该定时器一旦启动就调用SendImage()
这是我的接收代码:
BinaryFormatter binFormatter = new BinaryFormatter();
Image img = (Image)binFormatter.Deserialize(stream);
picturebox1.Image=img;
所以......什么错了?
答案 0 :(得分:0)
这很可能是由于错误使用Stream造成的。下面的代码工作正常:
private Image getScreen() {
Rectangle bound = Screen.PrimaryScreen.Bounds;
Bitmap ScreenShot = new Bitmap(bound.Width,bound.Height,PixelFormat.Format32bppArgb );
Graphics image = Graphics.FromImage(ScreenShot);
image.CopyFromScreen(bound.X,bound.Y,0,0,bound.Size,CopyPixelOperation.SourceCopy);
return ScreenShot;
}
private void SendImage(Stream stream) {
BinaryFormatter binFormatter = new BinaryFormatter();
binFormatter.Serialize(stream, getScreen());
}
void Main()
{
byte[] bytes = null;
using (var ms = new MemoryStream()) {
SendImage(ms);
bytes = ms.ToArray();
}
var receivedStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter();
Image img = (Image)binFormatter.Deserialize(receivedStream);
img.Save("c:\\temp\\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}