I have the following code (where res.shuffle
is an image, ein.Shuffle
is a bool and kontrast
is the kontrast-color of BackColor):
using (Bitmap img = Code.EditImageColor(res.shuffle, (ein.Shuffle ? BackColor : kontrast)))
{
pictureBox1.Image = img;
thumbnailToolbarButton1.Icon = Icon.FromHandle(img.GetHicon());
}
Here is the method for the image processing (in Code
class):
public static Bitmap EditImageColor(Image img, Color color)
{
Bitmap scrBitmap = new Bitmap(img);
Color oldcolor;
Bitmap newBitmap = new Bitmap(scrBitmap.Width, scrBitmap.Height);
for (int i = 0; i < scrBitmap.Width; i++)
{
for (int j = 0; j < scrBitmap.Height; j++)
{
oldcolor = scrBitmap.GetPixel(i, j);
newBitmap.SetPixel(i, j, Color.FromArgb(oldcolor.A, color));
}
}
return newBitmap;
}
But every time I run it, it says
System.ArgumentExeption (additional:
Invalid Parameters
)
pointing to the Application.Run(new Form1());
code block in my Program.cs
file.
StackTrace:
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll.
I also tried it with pictureBox1.Image
or thumbnailToolbarButton1.Icon
standing alone in the statement.
Why is this caused? And how to prevent it to cause?
Thanks for any help! :D
PS:
Sorry for any typos and if I've written something "contently wrong", due to I'm new to StackOverflow
.
So, very simple answer:
when the bitmap was set as image of pictureBox1, it gets disposed. (Thanks to @juharr for commenting this) Caused by disposing, the image gets invalid for the pictureBox & the exception will be thrown.
How to prevent this:
Don't use a using statement, just always use the same bitmap.
Bitmap imga = ...;
pictureBox0.Image = imga;
pictureBox1.Image = imga;
pictureBox2.Image = imga;
pictureBox3.Image = imga;
imga = ...;
pictureBox4.Image = imga;
pictureBox5.Image = imga;
pictureBox6.Image = imga;
pictureBox7.Image = imga;
...