2011-05-26 73 views

回答

2

您可以使用WritableBitmap,然後您可以使用BitmapEncoder對圖像進行編碼並保存。

var bitmap = new WriteableBitmap(100, 100, 96, 96, PixelFormats.Pbgra32, null); 
var rect = new Int32Rect(0, 0, 100, 100); 
var channelCount = 4; 
var pixels = new byte[100 * 100 * channelCount]; 
for (int i = 0; i < 100 * 100 * channelCount; i+=channelCount) 
{ 
    pixels[i + 2] = (byte)255; // Set red channel 
    pixels[i + 3] = (byte)255; // Set alpha channel 
} 
bitmap.WritePixels(rect, pixels, channelCount * 100, 0); 

var encoder = new PngBitmapEncoder(); 
encoder.Frames.Add(BitmapFrame.Create(bitmap)); 
using (var stream = new FileStream(@"C:\Users\Public\Test.png", FileMode.Create)) 
{ 
    encoder.Save(stream); 
} 
+0

@ H.B.Wouldü介意給確切的代碼。 – Vinod 2011-05-26 14:12:03

+0

是的,但我仍然添加它... – 2011-05-26 14:38:56

0

如果你想使用的形狀,而不是你能做到這一點

  var rtb = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); 

     var rectangle = new Rectangle(); 

     rectangle.BeginInit(); 
     rectangle.Height = 100; 
     rectangle.Width = 100; 
     rectangle.Stroke = Brushes.Red; 
     rectangle.Fill = Brushes.Red; 
     rectangle.StrokeThickness = 1.0; 
     rectangle.Margin = new Thickness(0, 0, 0, 0); 
     rectangle.EndInit(); 


     rectangle.Arrange(new Rect(new Size(100, 100))); 
     rectangle.UpdateLayout(); 

     rtb.Render(rectangle); 

     var png = new PngBitmapEncoder(); 
     png.Frames.Add(BitmapFrame.Create(rtb)); 
     using (Stream fs = File.Create("test.png")) 
     { 
      png.Save(fs); 
     } 
相關問題