调整图片的透明度,以及把透明背景改为其他颜色的方法


/// <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 System.Drawing.Image SetImageOpacity(System.Drawing.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 System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
return bmp;
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
return null;
}
}

/// <summary>
/// transparent2color
/// </summary>
/// <param name="bmp1"></param>
/// <param name="target"></param>
/// <returns></returns>
Bitmap Transparent2Color(Bitmap bmp1, System.Drawing.Color target)
{
Bitmap bmp2 = new Bitmap(bmp1.Width, bmp1.Height);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp1.Size);
using (Graphics G = Graphics.FromImage(bmp2))
{
G.Clear(target);
G.DrawImageUnscaledAndClipped(bmp1, rect);
}
return bmp2;
}

posted @ 2018-01-31 14:41  马肯尼煤牙巴骨  阅读(1456)  评论(0编辑  收藏  举报