如何检查位图图像是否为空?
How can I check if a Bitmap Image is empty?
在 Form1 中,我在构造函数中创建了一个新位图:
public Form1()
{
InitializeComponent();
de.pb1 = pictureBox1;
de.bmpWithPoints = new Bitmap(pictureBox1.Width, pictureBox1.Height);
de.numberOfPoints = 100;
de.randomPointsColors = false;
de.Init();
}
在 class 我检查位图是否为空 :
if (bmpWithPoints == null)
位图不为空,但也未在其上绘制任何内容。
我检查 class 如果它为空我想在位图上绘制和设置点。
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;
}
也许问题不应该是图像是否为空或null,我不确定如何调用它。也许只是一个新形象。但是我想检查一下如果新的位图是(空的)没有画在上面然后设置像素(点)。
您可以创建一种检查图像像素的方法。作为一种选择,您可以使用 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);
}
在 Form1 中,我在构造函数中创建了一个新位图:
public Form1()
{
InitializeComponent();
de.pb1 = pictureBox1;
de.bmpWithPoints = new Bitmap(pictureBox1.Width, pictureBox1.Height);
de.numberOfPoints = 100;
de.randomPointsColors = false;
de.Init();
}
在 class 我检查位图是否为空 :
if (bmpWithPoints == null)
位图不为空,但也未在其上绘制任何内容。 我检查 class 如果它为空我想在位图上绘制和设置点。
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;
}
也许问题不应该是图像是否为空或null,我不确定如何调用它。也许只是一个新形象。但是我想检查一下如果新的位图是(空的)没有画在上面然后设置像素(点)。
您可以创建一种检查图像像素的方法。作为一种选择,您可以使用 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);
}