加入收藏 | 设为首页 | 会员中心 | 我要投稿 温州站长网 (https://www.0577zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 系统 > 正文

.net – 移动设备上的OutOfMemoryException

发布时间:2021-02-23 15:49:28 所属栏目:系统 来源:网络整理
导读:我正在开发一个使用移动设备拍摄照片并使用网络服务发送的应用程序.但是在我拍了4张照片之后,我在下面的代码中得到了一个OutOfMemoryException.我试过调用GC.Collect()但它也没有帮助.也许这里有人可以给我一个如何处理这个问题的建议. public static Bitm

我正在开发一个使用移动设备拍摄照片并使用网络服务发送的应用程序.但是在我拍了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,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等有点谨慎,以确保尽快发布.

(编辑:温州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读