0

What am I trying to do?

The following function should simply return the image defined by parameter "sourceImage" with changed "opacity":

public static Image DisableImage(Image sourceImage)
        {
            Image newImage = new Bitmap(sourceImage);

            using (Graphics g = Graphics.FromImage(newImage))
            {
                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    ColorMatrix colorMatrix = new ColorMatrix();
                    colorMatrix.Matrix33 = 0.5f;
                    imageAttributes.SetColorMatrix(colorMatrix);

                    //Draw the original image on the new image using the color matrix
                    g.DrawImage(sourceImage, new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, imageAttributes);
                }
            }

            return newImage;
        }

What is the problem?

The returned image seems to be not changed at all.

What have I tried?

If changing the following line

ColorMatrix colorMatrix = new ColorMatrix();

to

ColorMatrix colorMatrix = new ColorMatrix(
                new float[][]{
                new float[] {0, 0, 0, 0, 0},
                new float[] {0, 0, 0, 0, 0},
                new float[] {0, 0, 0, 0, 0},
                new float[] {0, 0, 0, 1, 0},
                new float[] {Color.Red.R / 255.0f,
                             Color.Red.G / 255.0f,
                             Color.Red.B / 255.0f,
                             0, 1}
                });

a red half-transparent "film" is drawn on the image, which makes me suspect that I missed something in how to use the ColorMatrix.

Any help is appreciated, thanks!

JohnSaps
  • 602
  • 5
  • 16
  • [How to apply a fade transition effect to PictureBox Images using a Timer?](https://stackoverflow.com/a/61293719/7444103) -- [How can I gray-out a disabled PictureBox used as Button?](https://stackoverflow.com/a/61584671/7444103) – Jimi Aug 23 '21 at 07:23

1 Answers1

1

Alright, I figured it out myself.

Changing this line:

Image newImage = new Bitmap(sourceImage);

to

Image newImage = new Bitmap(sourceImage.Width, sourceImage.Height);

was the solution.

I was probably drawing on top of the existing image, which was of course not what I wanted. Any possibility to delete this question?

JohnSaps
  • 602
  • 5
  • 16