How to create an image and save it to a file in WPF
I 开发者_运维技巧want to create a new blank image of size 100x100. Paint it in red and save the image as 'test.png'. Can I access/change the pixel values of the created image. How can I do it in WPF.
You can use a WritableBitmap
for that, then you can use a BitmapEncoder
to encode the image and save it.
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);
}
If you wanna uses Shapes instead you can do this
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);
}
精彩评论