C# 中未将对象引用设置到对象的实例 急急急!!!

来源:百度知道 编辑:UC知道 时间:2024/07/06 14:18:34
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofdlg = new OpenFileDialog();
ofdlg.Filter = "Bmp File(*.bmp)|*.bmp";
if (ofdlg.ShowDialog() == DialogResult.OK)
{
Bitmap image = new Bitmap(ofdlg.FileName);
pictureBox1.Image = image;
}
}

private void b单色ToolStripMenuItem_Click(object sender, EventArgs e)
{
Bitmap b = new Bitmap(pictureBox1.Image);
Bitmap b1 = new Bitmap(pictureBox2.Image);
Color c = new Color();
Graphics g1 = pictureBox1.CreateGraphics();
for (int i = 0; i < pictureBox1.Width; i++)
{
for (int j = 0; j < pictureBox1.Height; j++)
{
c = b.GetPixel(i, j);
Color c1 = Color.FromArgb(c.B, c.B, c.B);
b1.SetPixel(i, j, c1);
}
pictureBox2.Refresh();
pictureBox2.Image = b1;
}
以上是将彩色图像转换为B单色图像的代码,但是调试的时候总出现“未将对象引用设置到对象的实例 ”这个错误,问题出在 Bitmap b1 = new Bitmap(pictureBox2.Image);这句,说是使用new关键字创建对象实例。
最近做毕

改成这样用好了
Bitmap flag = new Bitmap(200, 100);
Graphics flagGraphics = Graphics.FromImage(flag);
int red = 0;
int white = 11;
while (white <= 100) {
flagGraphics.FillRectangle(Brushes.Red, 0, red, 200,10);
flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);
red += 20;
white += 20;
}
pictureBox1.Image = flag;

就是让你先把结果修改到一个中间的图上,然后再绑到最后的picturebox,里面内容也要按你的自己改改

引用 private void b单色ToolStripMenuItem_Click(object sender, EventArgs e)

注意编码规范 不建议用中文来命名控件名称

因为Bitmap b1 = new Bitmap(pictureBox2.Image);的pictureBox2.Image为空,你还没有为pictureBox2.Image增加图片!所以错误!
你现在试一下随便给pictureBox2.Image增加一个图片就应该没事了。