2010-02-04 2 views
8

System.Drawing.Graphics.DrawImage은 하나의 이미지를 다른 이미지에 붙여 넣습니다. 하지만 투명성 옵션을 찾을 수 없었습니다.System.Drawing.Image를 반투명하게 만드는 방법은 무엇입니까?

이미 나는 이미지에서 원하는 모든 것을 그린

, 나는 단지 그것을 반투명 (알파 투명도)

+1

http://stackoverflow.com/questions/189392/how-do-you-draw-transparent-image-using-system-drawing –

+0

@Mitch 밀 - 그 질문에 GIF에만 해당 – Oded

+0

GIF에는 반투명이 없습니다. 나는 여기 PNGs에 대해 말하고있다 –

답변

11

수행하려는 작업을 알파 블렌딩이라고하기 때문에 "투명성"옵션이 없습니다.

public static class BitmapExtensions 
{ 
    public static Image SetOpacity(this Image image, float opacity) 
    { 
     var colorMatrix = new ColorMatrix(); 
     colorMatrix.Matrix33 = opacity; 
     var imageAttributes = new ImageAttributes(); 
     imageAttributes.SetColorMatrix(
      colorMatrix, 
      ColorMatrixFlag.Default, 
      ColorAdjustType.Bitmap); 
     var output = new Bitmap(image.Width, image.Height); 
     using (var gfx = Graphics.FromImage(output)) 
     { 
      gfx.SmoothingMode = SmoothingMode.AntiAlias; 
      gfx.DrawImage(
       image, 
       new Rectangle(0, 0, image.Width, image.Height), 
       0, 
       0, 
       image.Width, 
       image.Height, 
       GraphicsUnit.Pixel, 
       imageAttributes); 
     } 
     return output; 
    } 
} 

Alpha Blending

+1

[ColorMatrix] (http://msdn.microsoft.com/en-us/library/system.drawing.imaging.colormatrix (v = vs.110) .aspx) + [ImageAttributes] (http://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageattributes (v = vs.110) .aspx) + [SmoothingMode] (http : /msdn.microsoft.com/en-us/library/z714w2y9(v=vs.110).aspx) – Bitterblue

-1

내가 나를 위해 작동합니다 생각 미치 제공된 링크에서 답 복사 만들고 싶어 :

public static Bitmap SetOpacity(this Bitmap bitmap, int alpha) 
{ 
    var output = new Bitmap(bitmap.Width, bitmap.Height); 
    foreach (var i in Enumerable.Range(0, output.Palette.Entries.Length)) 
    { 
     var color = output.Palette.Entries[i]; 
     output.Palette.Entries[i] = 
      Color.FromArgb(alpha, color.R, color.G, color.B); 
    } 
    BitmapData src = bitmap.LockBits(
     new Rectangle(0, 0, bitmap.Width, bitmap.Height), 
     ImageLockMode.ReadOnly, 
     bitmap.PixelFormat); 
    BitmapData dst = output.LockBits(
     new Rectangle(0, 0, bitmap.Width, bitmap.Height), 
     ImageLockMode.WriteOnly, 
     output.PixelFormat); 
    bitmap.UnlockBits(src); 
    output.UnlockBits(dst); 
    return output; 
} 
+1

Bitmap.Pallete.Entries가 비어있어 작동하지 않았습니다. –

2
private Image GetTransparentImage(Image image, int alpha) 
{ 
    Bitmap output = new Bitmap(image); 

    for (int x = 0; x < output.Width; x++) 
    { 
     for (int y = 0; y < output.Height; y++) 
     { 
      Color color = output.GetPixel(x, y); 
      output.SetPixel(x, y, Color.FromArgb(alpha, color.R, color.G, color.B)); 
     } 
    } 

    return output; 
} 
관련 문제