我正在开发一个应用程序,该应用程序使用移动设备拍照并使用网络服务发送照片。但是在我拍了 4 张照片之后,我在下面的代码中得到了一个 OutOfMemoryException
。我尝试调用 GC.Collect()
但它也没有帮助。也许这里有人可以给我建议如何处理这个问题。
public static Bitmap TakePicture()
{
var dialog = new CameraCaptureDialog
{
Resolution = new Size(1600, 1200),
StillQuality = CameraCaptureStillQuality.Default
};
dialog.ShowDialog();
// If the filename is empty the user took no picture
if (string.IsNullOrEmpty(dialog.FileName))
return null;
// (!) The OutOfMemoryException is thrown here (!)
var bitmap = new Bitmap(dialog.FileName);
File.Delete(dialog.FileName);
return bitmap;
}
该函数由事件处理程序调用:
private void _pictureBox_Click(object sender, EventArgs e)
{
_takePictureLinkLabel.Visible = false;
var image = Camera.TakePicture();
if (image == null)
return;
image = Camera.CutBitmap(image, 2.5);
_pictureBox.Image = image;
_image = Camera.ImageToByteArray(image);
}
最佳答案
我怀疑您保留了引用资料。作为一个次要原因,请注意在使用 ShowDialog
时对话框不会自行处置,因此您应该使用
对话框(尽管我希望 GC 仍会收集未处置但未引用的对话框)。
同样,您可能应该使用
图像,但同样:不确定我是否希望它成败;不过值得一试...
public static Bitmap TakePicture()
{
string filename;
using(var dialog = new CameraCaptureDialog
{
Resolution = new Size(1600, 1200),
StillQuality = CameraCaptureStillQuality.Default
}) {
dialog.ShowDialog();
filename = dialog.FileName;
}
// If the filename is empty the user took no picture
if (string.IsNullOrEmpty(filename))
return null;
// (!) The OutOfMemoryException is thrown here (!)
var bitmap = new Bitmap(filename);
File.Delete(filename);
return bitmap;
}
private void _pictureBox_Click(object sender, EventArgs e)
{
_takePictureLinkLabel.Visible = false;
using(var image = Camera.TakePicture()) {
if (image == null)
return;
image = Camera.CutBitmap(image, 2.5);
_pictureBox.Image = image;
_image = Camera.ImageToByteArray(image);
}
}
我也会对 CutBitmap
等保持谨慎,以确保尽快发布内容。
关于.net - 移动设备上的 OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/593951/