将DrawingImage转换为BitmapImage
我想绘制大量的形状(线条,椭圆和……),然后将它们保存为位图或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而不是DrawingImage:
上述就是C#学习教程:将DrawingImage转换为BitmapImage分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1009046.html