Как решить исключение NullReferenceException в pictureBox?

В этом коде срабатывает исключение

Bitmap image1;
image1 = (Bitmap)pictureBox1.Image;
for (x = 0; x < image1.Width; x++)
                {
                    for (y = 0; y < image1.Height; y++)
                    {
                        image1.SetPixel(x, y, newColor);
                    }
                }

Срабатывает тогда, если я не загружаю изображение в pictureBox в этой строке

image1.SetPixel(x, y, newColor);

Как решить?


Ответы (1 шт):

Автор решения: Aziz Umarov

вот так сделайте

Bitmap image1;
image1 = (Bitmap)pictureBox1.Image;
if (image1 != null) {
for (x = 0; x < image1.Width; x++)
 {
   for (y = 0; y < image1.Height; y++)
   {
      image1.SetPixel(x, y, newColor);
   }
 }
}
→ Ссылка