我有这个方法应该截取屏幕截图并将图像返回给调用方法。
public static Bitmap TakeScreenshot(int x, int y, int height, int width)
{
Rectangle bounds = new Rectangle(0, 0, height, width);
Bitmap bitmap;
using (bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(x, y), Point.Empty, bounds.Size);
}
}
return bitmap;
}
问题在于,当我尝试保存图片时:
Bitmap bitmap = MyClass.TakeScreenshot(0, 0, 200, 200);
bitmap.Save(@"C:\test.jpg", ImageFormat.Jpeg);
然后我在save-method上遇到错误。
ArgumentException未处理。 参数无效。
如果我尝试将其保存在这样的方法中,它可以正常工作:
public static Bitmap TakeScreenshot(int x, int y, int height, int width)
{
Rectangle bounds = new Rectangle(0, 0, height, width);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(x, y), Point.Empty, bounds.Size);
}
bitmap.Save(@"c:\begin.tiff", ImageFormat.Tiff);
}
}
我在这里缺少什么?
答案 0 :(得分:7)
在您的第一个示例中,Bitmap
已通过using
声明处理,然后您将保存。
在第二个示例中,您将在处置之前保存。
您需要做的就是不将位图包装在using
语句中,而是将其留给垃圾收集器,或者在保存之后调用.Dispose()
。
就个人而言,对于实现IDisposable
接口的项目,我倾向于确保调用Dispose
,除非我的用法要求保持它活着。
答案 1 :(得分:3)
Bitmap
在被退回之前正在处理 - 也就是说,您正在返回已经IDisposable
调用的Dispose
对象:
using (bitmap = new Bitmap(bounds.Width, bounds.Height))
{
}
//using block makes sure Dispose is called when
//out of scope so this bitmap is no more
return bitmap;
如果你想使用方法范围之外的位图,那么你必须“释放所有权”(创建它,但不负责在该范围内销毁)并允许调用者管理它,并据此处理。
答案 2 :(得分:1)
如果你在使用块之外声明并访问Bitmap对象,那么不要使用using块:)我会这样编码:
public static Bitmap TakeScreenshot(int x, int y, int height, int width)
{
Rectangle bounds = new Rectangle(0, 0, height, width);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(new Point(x, y), Point.Empty, bounds.Size);
return bitmap;
}