分類:
GDI+
2011-07-24 01:13
121人閱讀
收藏
舉報
方法一:像素法即循環(huán)掃描整張圖片,設置每一個像素的Alpha通道的值。 由于是一個個像素的處理,所以這種方法效率很低。 -
-
-
-
-
-
- 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];
-
-
- System.Runtime.InteropServices.Marshal.Copy(ptr, argbValues, 0, bytes);
-
- for (int count = 3; count < argbValues.Length; count += 4)
- {
-
- 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++)
- {
-
- p[3] = (byte)alpha;
- p += 4;
- }
- p += offset;
- }
- }
-
- bmp.UnlockBits(bmpData);
- bitmap.Dispose();
-
- return bmp;
- }
方法四:矩陣法這個方法的效率最高。 -
-
-
-
-
-
- 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;
- }
|