首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >位图克隆上的C# WinForms内存异常

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

Stack Overflow用户
提问于 2013-09-26 17:16:21
回答 2查看 3.6K关注 0票数 2

我已经写了一个小的“水印”程序,以添加一个自定义水印到图像。有两个水印--白色的和黑色的。水印总是放置在图像的左边底部。我克隆图像的该区域,以确定在该点上应该放置哪个水印(光区域上的黑色水印和黑暗区域上的白色水印)。

当我在我的机器上使用应用程序时(无论是在调试中还是在正常状态下)--没有问题。对所有图像进行处理,并将水印添加到正确的位置。

但是,在客户端机器上,程序会中断在克隆部件上抛出OutOfMemory异常的所有图像。

我知道,通常情况下,当我指定一个超出界限的区域时,OutOfMemory异常也会被抛出,但是由于该函数在我的机器上的工作方式很有魅力,所以我无法想象会出现这种情况。除此之外,这个程序不会在几次尝试之后就崩溃,它会破坏所有的克隆尝试。

是否存在文本(DrawString方法)并不重要。它在克隆人身上破了。

正在处理的图像很大,但不是“巨大”(最多6016x4000像素),但即使是较小的图像(3264x2448像素),客户端也会中断。

变量:

bmOriginal:原始位图

processImage:原始图像(pictureBox) - bmOriginal是该文件的位图副本

watermarkText:在水印下面获取额外信息的文本框

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

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

代码:

代码语言:javascript
复制
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的异常。有什么主意吗?

编辑时,我选择不自动确定水印的颜色,只需添加一个水印(比如说白色的),程序正常运行。我在错误日志中看到了堆栈跟踪(在捕获函数时,我输出了异常和-if任意内部异常)。

我知道很多使用Clone函数的OOM异常都是在指定超出界限的区域时发生的;但是这里的情况并非如此。

当我在调试模式下使用应用程序时,当我查看我的内存时,我开始于5.36 Gb的程序开始,在运行我提到的执行时,标准化的5.39GB(最大峰值为5.42GB),它不是疯狂地消耗内存。

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

代码语言:javascript
复制
// 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);
}

源代码这里有一个测试项目:http://hotpepper.nu/oomtestapp.zip

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-27 11:35:44

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

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

不管怎样,我发现您使用ImageBox加载白色和黑色资源,并从磁盘加载图像。这根本不需要,整数直接使用资源。

代码语言:javascript
复制
Bitmap white = OomTestApp.Properties.Resources.white;
Bitmap black = OomTestApp.Properties.Resources.black;

然后,只需使用Bitmap.FromFile就可以从磁盘加载图像

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

我还删除了Clone()调用,因为它是绝对不需要的,因为您只是在计算原始图像的像素,并且没有在图像中画一些东西。那么,为什么需要克隆图像呢?

下面是完整的代码(从创建文件夹后开始)

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-03-16 21:21:30

嗯,我并没有读到页面上的所有内容,但我想知道是否有人提到了位图的“大步”?基本上,你的位图必须是4个字节的倍数。我有个问题,把网格拆开做瓷砖。最后一个平铺会出错,因为位图不能被4整除。

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

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19034524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档