gpt4 book ai didi

c# - 将 DrawingImage 转换为 BitmapImage

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:38 26 4
gpt4 key购买 nike

我想绘制大量形状(直线、椭圆和...),然后将它们保存为位图或 png。我画了图,问题是:如何在 C# 中将 DrawingImage 转换为 BitmapImage?代码是这样的:

DrawingGroup drawingGroup = new DrawingGroup();
using(DrawingContext context = drawingGroup.Open())
{
//make some drawing
}
DrawingImage drawingImage = new DrawingImage(drawingGroup)

// your suggestion? DrawingImage - > BitmapImage

最佳答案

您可以将 ImageDrawing 放入 Image 控件中并将其渲染到 RenderTargetBitmap 中,它是一个 BitmapSource,因此可以由 BitmapEncoder 序列化。 (本例中为 PngBitmapEncoder)。

public void SaveDrawingToFile(Drawing drawing, string fileName, double scale)
{
var drawingImage = new Image { Source = new DrawingImage(drawing) };
var width = drawing.Bounds.Width * scale;
var height = drawing.Bounds.Height * scale;
drawingImage.Arrange(new Rect(0, 0, width, height));

var bitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(drawingImage);

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));

using (var stream = new FileStream(fileName, FileMode.Create))
{
encoder.Save(stream);
}
}

请注意,您实际上不需要 BitmapImage 进行编码,因为 BitmapSource(或任何派生类,如 RenderTargetBitmap)将被接受为 BitmapFrame.Create 的参数。 .


稍微不同的解决方案将涉及 DrawingVisual而不是绘图图像:

public void SaveDrawingToFile(Drawing drawing, string fileName, double scale)
{
var drawingVisual = new DrawingVisual();

using (var drawingContext = drawingVisual.RenderOpen())
{
drawingContext.PushTransform(new ScaleTransform(scale, scale));
drawingContext.PushTransform(new TranslateTransform(-drawing.Bounds.X, -drawing.Bounds.Y));
drawingContext.DrawDrawing(drawing);
}

var width = drawing.Bounds.Width * scale;
var height = drawing.Bounds.Height * scale;
var bitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(drawingVisual);

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));

using (var stream = new FileStream(fileName, FileMode.Create))
{
encoder.Save(stream);
}
}

关于c# - 将 DrawingImage 转换为 BitmapImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14387350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com