位图意外退出循环没有错误 [英] Bitmap unexpected exiting loop without error

查看:94
本文介绍了位图意外退出循环没有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Community,

我在使用位图进行计算时遇到问题。我想得到位图(659 x 494)和亮度值矩阵的总和亮度。为此,我从这里结合了一些有用的文章。



这是代码:

Hello Community,
I am encountering a problem while doing some calculation with a bitmap. I want to get the summed up brightness of a bitmap (659 x 494) and a matrix with the brightness values. To do that I combined some helpful articles from here.

Here is the code:

public static double CALC_BRIGHTNESS(Bitmap bm)
        {
            double lum = 0;
            var tmpBmp = new Bitmap(bm);
            var width = bm.Width;
            var height = bm.Height;
            var bppModifier = bm.PixelFormat == PixelFormat.Format24bppRgb ? 3 : 4;

            var srcData = tmpBmp.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, bm.PixelFormat);
            var stride = srcData.Stride;
            var scan0 = srcData.Scan0;

            unsafe
            {
                int bytes = Math.Abs(stride) * tmpBmp.Height;
                byte[] p = new byte[bytes];
                System.Runtime.InteropServices.Marshal.Copy(scan0, p, 0, bytes);

                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        int idx = (y * stride) + x * bppModifier;
                        double lumin = (0.299 * p[idx + 2] + 0.587 * p[idx + 1] + 0.114 * p[idx]) / 255.00;
                        pixels[x, y] = lumin;
                        if (lumin >= border)
                            lum += lumin;
                    }
                    
                }
            }

            tmpBmp.UnlockBits(srcData);
            tmpBmp.Dispose();
            return lum;
        }





但它始终退出for循环,其中y = 491,x = 494,idx = 327640。计算不继续,表格显示,可以关闭...

小图片(约300 x 200)我没有任何问题。

也许你们其中一个可以帮我解决这个问题。



But it is always exiting the for loops where y = 491, x = 494 and idx = 327640. Following calculations are not continued, the Form is shown and can be closed...
With a smaller picture(approx 300 x 200) I don't have any issues.
Maybe one of you can help me solve this issue.

推荐答案

开始尝试捕捉你的代码并在MessageBox中显示任何错误。

Start to put a try catch around your code and show any error in a MessageBox.
public static double CALC_BRIGHTNESS(Bitmap bm)
{
    Bitmap tmpBmp = null;  // Declare this variable outside the try-catch block
                           // and call dispose in finally
    try
    {
        // Your code
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString));
    }
    finally
    {
        if (tmpBmp != null)
            tmpBmp.Dispose();
    }
}





另外变量的方式和位置像素声明?


这篇关于位图意外退出循环没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆