0

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.

hcerim
  • 959
  • 1
  • 11
  • 27
  • Are you sure `TestButton.Image` is not null? Also your extension method is called `ChangeOpacity` and in your example your are calling `SetImageOpacity` (maybe a typo). Finally, as it expects a float, it should be `. ChangeOpacity(0.1f);` – Pikoh May 24 '17 at 06:59
  • I have set it in the Properties of TestButton. So I think it shold not be null after call 'InitializeComponent()'. But I will try your suggestion to debug it. – Alan Ackart May 24 '17 at 07:04
  • @Pikoh, Yes, You are right the TestButton.Image is null. – Alan Ackart May 24 '17 at 07:10

0 Answers0