【问题标题】:How can I check if a Bitmap Image is empty?如何检查位图图像是否为空?
【发布时间】:2016-12-22 20:03:30
【问题描述】:

在 Form1 中,我在构造函数中创建了一个新的位图:

public Form1()
{
    InitializeComponent();
    de.pb1 = pictureBox1;
    de.bmpWithPoints = new Bitmap(pictureBox1.Width, pictureBox1.Height);
    de.numberOfPoints = 100;
    de.randomPointsColors = false;
    de.Init();
}

在课堂上我检查位图是否为空:

if (bmpWithPoints == null)

位图不为空,但也没有绘制任何内容。 我检查类是否为空我想在位图上绘制和设置点。

if (bmpWithPoints == null)
{
    for (int x = 0; x < bmpWithPoints.Width; x++)
    {
        for (int y = 0; y < bmpWithPoints.Height; y++)
        {
            bmpWithPoints.SetPixel(x, y, Color.Black);
        }
    }
    Color c = Color.Red;
    for (int x = 0; x < numberOfPoints; x++)
    {
        for (int y = 0; y < numberOfPoints; y++)
        {
            if (randomPointsColors == true)
            {
                c = Color.FromArgb(
                    r.Next(0, 256),
                    r.Next(0, 256),
                    r.Next(0, 256));
            }
            else
            {
                c = pointsColor;
            }
            bmpWithPoints.SetPixel(r.Next(0, bmpWithPoints.Width), 
                r.Next(0, bmpWithPoints.Height), c);
        }
    }
}
else
{
    randomPointsColors = false;
}

也许问题不应该是图像是空的还是空的,我不知道如何调用它。也许只是一个新形象。但我想检查新位图是否(空)上没有绘制然后设置像素(点)。

【问题讨论】:

标签: c# .net winforms bitmap gdi+


【解决方案1】:

您可以创建一个检查图像像素的方法。作为一个选项,您可以使用LockBits 方法将位图字节放入字节数组并使用它们:

bool IsEmpty(Bitmap image)
{
    var data = image.LockBits(new Rectangle(0,0, image.Width,image.Height),
        ImageLockMode.ReadOnly, image.PixelFormat);
    var bytes = new byte[data.Height * data.Stride];
    Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
    image.UnlockBits(data);
    return bytes.All(x => x == 0);
}

【讨论】:

  • 取决于你对“空”的定义……隐形粉红独角兽是“空”的形象吗?如果一种颜色有值但它的 alpha 为 0,那么它是“空的”但与您的检查不匹配。更不用说,stride 超出宽度的字节......它们可以是内存中留下的任何垃圾。
猜你喜欢
  • 2014-01-10
  • 1970-01-01
  • 2018-04-28
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多