您的位置:首页 > 其它

设置图片透明度的四种方法

2011-07-24 01:13 274 查看

方法一:像素法

即循环扫描整张图片,设置每一个像素的Alpha通道的值。 由于是一个个像素的处理,所以这种方法效率很低。
/// <summary>
/// 设置图片的透明度
/// </summary>
/// <param name="bitmap">原图</param>
/// <param name="alpha">透明度(0-255之间)</param>
/// <returns></returns>
public static Bitmap SetBitmapAlpha(Bitmap bitmap, int alpha)
{
Bitmap bmp = (Bitmap)bitmap.Clone();
Color color;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
color = bmp.GetPixel(x, y);
bmp.SetPixel(x, y, Color.FromArgb(alpha, color));
}
}

bitmap.Dispose();
return bmp;
}


方法二:内存法

public static Bitmap SetBitmapAlpha(Bitmap bitmap, int alpha)
{
Bitmap bmp = (Bitmap)bitmap.Clone();

Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb);

IntPtr ptr = bmpData.Scan0;  //获取首地址
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] argbValues = new byte[bytes];

//复制ARGB的值到数组
System.Runtime.InteropServices.Marshal.Copy(ptr, argbValues, 0, bytes);

for (int count = 3; count < argbValues.Length; count += 4)
{
//设置alpha通道的值
argbValues[count] = (byte)alpha;
}

System.Runtime.InteropServices.Marshal.Copy(argbValues, 0, ptr, bytes);
bmp.UnlockBits(bmpData);

bitmap.Dispose();
return bmp;
}


方法三:指针法

public static Bitmap SetBitmapAlpha(Bitmap bitmap, int alpha)
{
Bitmap bmp = (Bitmap)bitmap.Clone();

Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect,
ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

unsafe
{
byte* p = (byte*)bmpData.Scan0;
int offset = bmpData.Stride - bmp.Width * 4;
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
//设置alpha通道的值
p[3] = (byte)alpha;
p += 4;
}
p += offset;
}
}

bmp.UnlockBits(bmpData);
bitmap.Dispose();

return bmp;
}


方法四:矩阵法

这个方法的效率最高。
/// <summary>
/// 设置图片的透明度
/// </summary>
/// <param name="image">原图</param>
/// <param name="alpha">透明度0-255</param>
/// <returns></returns>
private Bitmap SetPictureAlpha(Image image,int alpha)
{
//颜色矩阵
float[][] matrixItems =
{
new float[]{1,0,0,0,0},
new float[]{0,1,0,0,0},
new float[]{0,0,1,0,0},
new float[]{0,0,0,alpha/255f,0},
new float[]{0,0,0,0,1}
};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
Bitmap bmp = new Bitmap(image.Width, image.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAtt);
g.Dispose();

return bmp;
}


注意:需要添加命名空间System.Drawing和ystem.Drawing.Imaging。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: