Here is the extension method(I just add this
, the rest of the code is from [CodeProject]:https://www.codeproject.com/Tips/201129/Change-Opacity-of-Image-in-C ),
public static Bitmap ChangeOpacity(this Image img, float opacityvalue)
{
Bitmap bmp = new Bitmap(img.Width,img.Height); // Determining Width and Height of Source Image
Graphics graphics = Graphics.FromImage(bmp);
ColorMatrix colormatrix = new ColorMatrix();
colormatrix.Matrix33 = opacityvalue;
ImageAttributes imgAttribute = new ImageAttributes();
imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
graphics.Dispose(); // Releasing all resource used by graphics
return bmp;
}
I want to use it to change the opacity of the image of a button in the follwoing way,
public Form04_mainMenu()
{
InitializeComponent();
this.TestButton.Image = this.TestButton.Image.SetImageOpacity(0.1);
}
But I got NullReferenceException
in Bitmap bmp = new Bitmap(img.Width,img.Height);
I understand what does NullReferenceException
mean, but don't know how to solve it. Any help would be appreciated.