天天看点

c# 调整图像透明度

/// <summary>
/// 透明度调整
/// </summary>
/// <param name="image"></param>
/// <param name="opacity">  0.1  -- 1 </param>
/// <returns></returns>
public Image ToTransparent(Image image, float opacity)
{
    if (opacity >= 1 || opacity < 0) return image;//透明度应在0.1 - 1之间
    Bitmap bitmap = new Bitmap(image.Width, image.Height);
    using (var g = Graphics.FromImage(bitmap))
    {
        var matrix = new ColorMatrix { Matrix33 = opacity };
        var attributes = new ImageAttributes();
        attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        var rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
        g.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
    }
    return bitmap;
}