C# image opacity

Question:

Good morning, I came across a problem in my Windows Form C# application , I'm trying to apply an image with low opacity (transparency) in the background to my panel1 , but the image when inserted has 100% opacity, giving conflict with what is over the background. First I tried to just put the image as the background of the panel and it didn't work. As I work with Bitmaps I can use transparent background I thought it could be the solution to the problem, but without success too. Can something be done so that the image does not lose its transparency ?

Bitmap config;

private void FormConfig_Load(object sender, EventArgs e)
{
    config = new Bitmap(@"C:\Users\...\background_config.png"); //imagem quase transparente
}

private void panel1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(config, new Point(0, 0));
}

Answer:

Example found in Change Opacity of Image in C# :

/// <summary>  
/// method for changing the opacity of an image  
/// </summary>  
/// <param name="image">image to set opacity on</param>  
/// <param name="opacity">percentage of opacity</param>  
/// <returns></returns>  
public Image SetImageOpacity(Image image, float opacity)  
{  
    try  
    {  
        //create a Bitmap the size of the image provided  
        Bitmap bmp = new Bitmap(image.Width, image.Height);  

        //create a graphics object from the image  
        using (Graphics gfx = Graphics.FromImage(bmp)) {  

            //create a color matrix object  
            ColorMatrix matrix = new ColorMatrix();      

            //set the opacity  
            matrix.Matrix33 = opacity;  

            //create image attributes  
            ImageAttributes attributes = new ImageAttributes();      

            //set the color(opacity) of the image  
            attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);    

            //now draw the image  
            gfx.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
        }
        return bmp;  
    }  
    catch (Exception ex)  
    { 
        MessageBox.Show(ex.Message);  
        return null;  
    }  
} 

Issue also discussed in SOen in the topic Changing the Opacity of a Bitmap image .

Scroll to Top