Opacity of images C#

Asked

Viewed 285 times

3

Good morning, I came across a problem in my application Windows Form C#, I’m trying to apply an image with low opacity() background to my panel1, but the image when inserted gets 100% opacity, giving conflict with what is above the background. I first tried to put the image as the background of the panel and it didn’t work. As working with Bitmaps I can use transparent background I thought it could be the solution to the problem, but without success as well. Something can be done so that the image does not lose the 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));
}
  • Felipe, good morning to you! I’m not using code to test the Bitmap class, but there’s no Overload on it that tells you the type of extension or something like that when you upload the image?

1 answer

2


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 on the topic Changing the Opacity of a Bitmap image.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.