我正在开发一个使用移动设备拍摄照片并使用网络服务发送的应用程序.但在我拍了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); }
Marc Gravell.. 5
我怀疑你正在坚持参考.作为一个次要原因,请注意对话框在使用时不会自行处理ShowDialog
,因此您应该成为using
对话框(尽管我希望GC仍然可以收集一个未曝光但未引用的对话框).
同样地,你可能应该using
是形象,但是又一次:不确定我是否会期待这种形成或断裂; 值得一试,但......
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
等等保持谨慎,以确保尽快发布.
我怀疑你正在坚持参考.作为一个次要原因,请注意对话框在使用时不会自行处理ShowDialog
,因此您应该成为using
对话框(尽管我希望GC仍然可以收集一个未曝光但未引用的对话框).
同样地,你可能应该using
是形象,但是又一次:不确定我是否会期待这种形成或断裂; 值得一试,但......
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
等等保持谨慎,以确保尽快发布.