c# - 在循环中创建位图时出现内存溢出异常

标签 c# memory bitmap overflow imaging

我必须从许多已准备好存储在我的数据库中的图像中导入大量图像裁剪。我每次都尝试使用语句并处理我的位图对象。但我仍然收到内存溢出异常,提示我的系统内存不足。

这是我正在做的一些示例代码。

public void CropImage(List<ImageClass> data)
{
    foreach (var obj in data)
    {
        //I have a data base method that returns a data object that 
        //contains the file bytes of the image id in data: 'file'
        //My List<ImageClass> data contains an ID of the original image
        //start x,y coords for the upper left corner of the rectangle,
        //and the width and height of the rectangle.

        Image img = Image.FromStream(new MemoryStream(file.Data));
        Bitmap bmp = new Bitmap((Bitmap)img);
        Rectangle cropArea = new Rectangle(obj.x_coordinate,
                                           obj.y_coordinate,
                                           obj.width,
                                           obj.height);

        Bitmap cropImage = bmp.Clone(cropArea, bmp.PixelFormat);

        SaveFile(cropImage, file, obj.scanID);

        img.Dispose();
        bmp.Dispose();
        cropImage.Dispose();
    }
}


    public void SaveFile(Bitmap cropImage, FileData file, int OCRscanID)
    {
        EncoderParameters encoderParams = new EncoderParameters();
        encoderParams.Param[0] = new EncoderParameter(
                                          System.Drawing.Imaging.Encoder.Quality,
                                          50L);

        ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
        MemoryStream newImage = new MemoryStream();
        cropImage.Save(newImage, codecInfo, encoderParams);

        byte[] newData = newImage.ToArray();

        //Saving data bytes to database of the cropped image 
    }

    private ImageCodecInfo GetEncoderInfo(string mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }

我知道我可以精简一些代码,例如搜索编码器以仅使用图像/jpeg。但是我有这个代码另一个项目的另一个应用程序。我似乎无法克服内存溢出问题。

我需要循环浏览大约 2 万张图片。

最佳答案

您并没有处置您的内存流。所有实现了 IDisposable 的东西都应该被释放。

Is a memory leak created if a MemoryStream in .NET is not closed?

关于c# - 在循环中创建位图时出现内存溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6618644/

相关文章:

android - 如何绘制平滑的位图路径,没有任何中断

c# - 在处理非常大的图像时如何避免位图内存不足,即 : 10. 000.000 像素及以上

c# - 如何将颜色转换为代码,反之亦然

c - 内存中的值如何与变量及其类型相关联?

c - 学习 C 试图通过函数找出这个 malloc 的东西

c++ - 将读取的内存过程存储在缓冲区中,然后对其进行搜索

android - 我可以在 @Composable 之外使用 Jetpack 撰写图标吗?

c# - 删除 Service Fabric App 后进程仍在运行

c# - 更改除单击按钮之外的所有按钮背景

c# - checked 和 unchecked 有什么区别?