位图克隆上的C#WinForms内存异常

时间:2013-09-26 17:16:22

标签: c# winforms bitmap system.drawing

我写了一个小的“水印”程序,为图像添加自定义水印。有两个水印,一个是白色,另一个是黑色。水印始终位于图像的左下侧。我克隆图像的那个区域,以确定应该根据该点放置哪个水印(浅色区域的黑色水印和暗区域的白色水印)。

当我在我的机器上使用应用程序(在调试或正常情况下)时没问题。处理所有图像并在正确的位置添加水印。

但是,在客户端计算机上,程序会破坏在克隆部分上抛出OutOfMemory异常的所有图像。

我知道,当我指定一个超出范围的区域时,也会抛出OutOfMemory Exception,但由于该函数在我的机器上像魅力一样工作,我无法想象是这种情况。除此之外,程序在几次尝试后不会中断,它会破坏所有克隆尝试。

是否有文本(DrawString方法)无关紧要。它破坏了克隆人。

正在处理的图像很大,但不是“巨大”(最多6016 x 4000像素),但即使图像较小(3264 x 2448像素),客户端也会破坏。

变量:

bmOriginal:原始位图

processImage:原始图片(pictureBox) - bmOriginal是此

的位图副本

watermarkText:文字框,了解水印以下的额外信息

blackwhite:包含水印图片的图片框

watermarkCombo:用于选择自动,白色或黑色(自动失败)的组合框

代码:

using (Graphics gWatermark = Graphics.FromImage(bmOriginal))
{
    gWatermark.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

    // position watermark - watermark should be 10% of the image height
    int watermarkHeight = (int)(processImage.Image.Height * 0.1);
    int watermarkPadding = (int)(watermarkHeight * 0.1); // not completely true, but asume watermark is square
    Rectangle watermarkArea = new Rectangle(watermarkPadding, processImage.Image.Height - (watermarkPadding + (watermarkText.Text.Length == 0 ? 0 : watermarkPadding) + watermarkHeight), watermarkHeight, watermarkHeight);

    // determine color watermark
    bmWatermark = (Bitmap)black.Image;
    if (watermarkCombo.SelectedIndex == 0)
    {
        using (Bitmap watermarkClone = bmOriginal.Clone(watermarkArea, bmOriginal.PixelFormat))
        {
            var pixels = Pixels(watermarkClone);
            if (pixels.Average((Func<Color, decimal>)Intensity) < 110) // human eye adoption; normal threshold should be 128
            {
                bmWatermark = (Bitmap)white.Image;
                drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
            }
        }
    }
    else if (watermarkCombo.SelectedIndex == 1)
    {
        bmWatermark = (Bitmap)white.Image;
        drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
    }

    // draw the watermark
    gWatermark.DrawImage(bmWatermark, watermarkArea.X, watermarkArea.Y, watermarkArea.Width, watermarkArea.Height);

    // draw the text (if needed)
    if (watermarkText.Text.Length > 0)
    {
        System.Drawing.Font drawFont = new System.Drawing.Font("Tahoma", (float)watermarkPadding);
        gWatermark.DrawString(watermarkText.Text, drawFont, drawBrush, watermarkPadding, bmOriginal.Height - (watermarkPadding * 2));
    }
}
bmOriginal.Save(System.IO.Path.Combine(diWatermarked.FullName, fileName), System.Drawing.Imaging.ImageFormat.Jpeg);

错误行:using (Bitmap watermarkClone = bmOriginal.Clone(watermarkArea, bmOriginal.PixelFormat))

现在最大的问题是:如何摆脱OutOfMemory异常......任何人都有想法?

编辑当我选择不自动确定水印的颜色并只添加水印(假设是白色水印)时,程序正常运行。我在错误日志中看到了堆栈跟踪(在我输出异常的函数的catch上,以及-if-内部异常)。

我知道当你指定一个超出界限的区域时,会发生很多使用克隆功能的OOM异常;但这不是这种情况。

当我在调试模式下使用应用程序时查看我的内存时,我在5.36 Gb程序启动时启动,并在运行执行时启动标准化的5.39 Gb(最大峰值为5.42 Gb)提到,它并不像疯了一样耗费精力。

我使用的代码确定平均“颜色”(它来自StackOverflow上的某个人 - 我只是从其他答案中复制了它,但是找不到链接);

// functions used to determine watermark color
private static decimal ComponentAverage(decimal a, decimal b)
{
    return Math.Min(a, b) + Math.Abs(a - b) / 2M;
}
private static decimal Intensity(Color color)
{
    decimal result = color.A;
    result = ComponentAverage(result, color.R);
    result = ComponentAverage(result, color.G);
    result = ComponentAverage(result, color.B);
    return result;
}
private static IEnumerable<Color> Pixels(Bitmap bitmap)
{
    for (int x = 0; x < bitmap.Width; x++)
        for (int y = 0; y < bitmap.Height; y++)
            yield return bitmap.GetPixel(x, y);
}

SOURCE 此处有一个测试项目:http://hotpepper.nu/oomtestapp.zip

2 个答案:

答案 0 :(得分:1)

Leon,我已将您上传的代码更改为不锁定任何资源。 我注意到,如果我保持应用程序打开,我无法删除输出文件夹,因为某些文件正在使用中。这通常意味着您不能释放所有文件句柄,基本上它始终是最后一个文件。

我无法在我的更改之前和之后重现我的计算机上的内存不足问题,似乎是一个非常大的文件的问题?

好吧无论如何,我发现你使用ImageBox来加载白色和黑色资源并从光盘加载图像。这根本不需要,直接使用资源

Bitmap white = OomTestApp.Properties.Resources.white;
Bitmap black = OomTestApp.Properties.Resources.black;

然后从光盘加载图片,只需使用 Bitmap.FromFile

我添加了一些行来正确释放资源.Dispose,其中没有使用using块。

我还删除了Clone()调用因为我认为绝对不需要它,因为你只是在计算原始图像的像素,而在此时你不会在该图像中绘制某些东西。那么克隆图像需要什么呢?

以下是完整代码(在创建文件夹后开始)

if (errors == 0)
{
this.Height = 323;
goButton.Enabled = false;
stopButton.Enabled = true;

Bitmap white = OomTestApp.Properties.Resources.white;
Bitmap black = OomTestApp.Properties.Resources.black;
Bitmap bmWatermark = black;
Bitmap processImage = null;


progressBar1.Maximum = filesToProcess.Count;

foreach (string handleFile in filesToProcess)
{
    string fileName = System.IO.Path.GetFileName(handleFile);
    fileNameLabel.Text = "File: " + System.IO.Path.GetFileName(handleFile);
    try
    {
        // create backup if checked
        if (diOriginal != null)
        {
            System.IO.File.Move(handleFile, System.IO.Path.Combine(diOriginal.FullName, fileName));
            processImage = (Bitmap)Bitmap.FromFile(System.IO.Path.Combine(diOriginal.FullName, fileName));
        }
        else
        {
            processImage = (Bitmap)Bitmap.FromFile(handleFile);
        }

        double aspectRatio = (double)processImage.Width / (double)processImage.Height;

        using (Graphics gWatermark = Graphics.FromImage(processImage))
        {
            gWatermark.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

            // position watermark - watermark should be 10% of the image height
            int watermarkHeight = (int)(processImage.Height * 0.1);
            int watermarkPadding = (int)(watermarkHeight * 0.1); // not completely true, but asume watermark is square
            // calculate rectangle. if there is extra text, add extra padding below
            Rectangle watermarkArea = new Rectangle(watermarkPadding, processImage.Height - (watermarkPadding + (watermarkText.Text.Length == 0 ? 0 : watermarkPadding) + watermarkHeight), watermarkHeight, watermarkHeight);

            // determine color watermark
            bmWatermark = black;
            if (watermarkCombo.SelectedIndex == 0)
            {
                /*using (Bitmap watermarkClone = processImage.Clone(watermarkArea, processImage.PixelFormat))
                {*/
                var pixels = Pixels(processImage);
                if (pixels.Average((Func<Color, decimal>)Intensity) < 110) // human eye adoption; normal threshold should be 128
                {
                    bmWatermark = white;
                    drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
                }
                //}
            }
            else if (watermarkCombo.SelectedIndex == 1)
            {
                bmWatermark = white;
                drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
            }

            // draw the watermark
            gWatermark.DrawImage(bmWatermark, watermarkArea.X, watermarkArea.Y, watermarkArea.Width, watermarkArea.Height);

            // draw the text (if needed)
            if (watermarkText.Text.Length > 0)
            {
                System.Drawing.Font drawFont = new System.Drawing.Font("Tahoma", (float)watermarkPadding);
                gWatermark.DrawString(watermarkText.Text, drawFont, drawBrush, watermarkPadding, processImage.Height - (watermarkPadding * 2));
                drawFont.Dispose();
            }
            // disposing resources
            drawBrush.Dispose();

        }
        // save the watermarked file
        processImage.Save(System.IO.Path.Combine(diWatermarked.FullName, fileName), System.Drawing.Imaging.ImageFormat.Jpeg);


        // stop button pressed?
        Application.DoEvents();
        if (stopProcess) break;

        // update exection progress
        progressBar1.Value++;
        percentLabel.Text = ((int)((progressBar1.Value * 100) / filesToProcess.Count)).ToString() + "%";
        fileCountLabel.Text = "File " + progressBar1.Value.ToString() + "/" + filesToProcess.Count.ToString();
    }
    catch (Exception ex)
    {
        try
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.Combine(folderText.Text, "errorlog.txt"), true))
            {
                sw.WriteLine("File: " + fileName);
                while (ex != null)
                {
                    sw.WriteLine("Message: " + ex.Message);
                    sw.WriteLine(ex.StackTrace);
                    sw.WriteLine(ex.Source);
                    ex = ex.InnerException;
                }
                sw.WriteLine();
            }
        }
        catch
        {
            // nothing to do - it already failed
        }
        errors++;
    }
    finally
    {
        if (processImage != null) processImage.Dispose();
    }
}

// dispose resources
white.Dispose();
black.Dispose();
bmWatermark.Dispose();



if (!stopProcess)
{
    // set status to complete
    fileCountLabel.Text = "File " + filesToProcess.Count.ToString() + "/" + filesToProcess.Count.ToString();
    percentLabel.Text = "100%";
    fileNameLabel.Text = "Completed...";
}
else
{
    fileNameLabel.Text = "Aborted...";
}

fileNameLabel.Text += errors.ToString() + " error(s) encountered";

// defaults to screen
progressBar1.Value = progressBar1.Maximum;
stopProcess = false;
goButton.Enabled = true;
stopButton.Enabled = false;

答案 1 :(得分:-1)

好吧,我没有阅读页面上的所有内容,但我想知道是否有人提到过Bitmap的“步幅”?基本上,您的位图必须是4个字节的倍数。 我有这个问题拆开网格来制作瓷砖。最后一个图块会出错,因为Bitmap不能被4整除。

  

步幅是单行像素(扫描线)的宽度,   四舍五入到四字节边界。如果步幅是积极的,那么   位图是自上而下的。如果步幅为负,则位图为   自下而上。   https://softwarebydefault.com/2013/04/11/bitmap-color-balance/