Changing the Opacity of a Bitmap image

前端 未结 4 1330
暗喜
暗喜 2020-12-05 04:58

I have a form which has a image. I am using a slider to change the opacity of the image. So in the \"ValueChanged\" event of the slider I am calling the following method to

4条回答
  •  伪装坚强ぢ
    2020-12-05 05:27

    Try this one from CodeProject - Change Opacity of Image in C#:

    ///   
    /// method for changing the opacity of an image  
    ///   
    /// image to set opacity on  
    /// percentage of opacity  
    ///   
    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;  
        }  
    } 
    

提交回复
热议问题