2009-08-31 19 views
2

私は他の画像の上に重ねることができるように、白のアルファに置き換えられた色で表示する画像を取得しようとしています。私は色を簡単に変えることができるようにしましたが、透明に変えることは私を逃すことです。ここで私のコードは、C#とWPFを使用しています。画像操作でのアルファの使用

private void SetAlpha(string location) 
    { 
     //bmp is a bitmap source that I load from an image 
     bmp = new BitmapImage(new Uri(location)); 
     int[] pixels = new int[(int)bmp.Width * (int)bmp.Height]; 
     //still not sure what 'stride' is. Got this part from a tutorial 
     int stride = (bmp.PixelWidth * bmp.Format.BitsPerPixel + 7)/8; 

     bmp.CopyPixels(pixels, stride, 0); 
     int oldColor = pixels[0]; 
     int red = 255; 
     int green = 255; 
     int blue = 255; 
     int alpha = 0; 
     int color = (alpha << 24) + (red << 16) + (green << 8) + blue; 

     for (int i = 0; i < (int)bmp.Width * (int)bmp.Height; i++) 
     { 
      if (pixels[i] == oldColor) 
      { 
       pixels[i] = color; 
      } 
     } 
      //remake the bitmap source with these pixels 
      bmp = BitmapSource.Create(bmp.PixelWidth, bmp.PixelHeight, bmp.DpiX, bmp.DpiY, bmp.Format, bmp.Palette, pixels, stride); 
     } 

    } 

これをテストしている画像が2つあります。 Image1は、私が取り組んでいるもののようで、元の画像に透明性がありません。 Image2はすでに透過性を持っています。 image2(0x00ffffff)から値を取得するのは簡単だと思っていましたが、それは白くなり、後ろの画像を覆い隠してしまいます。

両方の画像はpngで、両方の形式はBgr32です。

画像を透明にする方法を知っている人はいますか?

答えて

3

Bgra32はどうですか?

また、色がメモリ内でどのように表されているか、そしてalphaの意味を理解していることを確認してください。

+0

ありがとうございます! bmp = BitmapSource.Create(bmp.PixelHidth、bmp.DpiX、bmp.DpiY、bmp.Format、bmp.Palette、pixels、stride);を変更します。 〜 bmp = BitmapSource.Create(bmp.PixelWidth、bmp.PixelHeight、bmp.DpiX、bmp.DpiY、bmp.Format、bmp.Palette、pixels、stride); を修正しました。 私はあなたに緊張している色を使って何かしていますか? – Califer

+0

いいえ...それはかなり大丈夫です。 –

+0

おっと、私は実際に修正プログラムを投稿していませんでした:P第2のbmp.Formatは 'System.Windows.Media'でなければなりません。あなたはあなたが何をしているのかを理解しようとしていました。代わりにPixelFormats.Bgra32 'を使用します。 – Califer