C# WPF 如何将字节数组转换为InkCanvas的StrokeCollection
解决方法
你需要实现的DisplayCanvasStrokeBytes方法可以直接通过StrokeCollection原生的流构造函数完成还原,和你保存时的Save逻辑完全对应,实现代码如下:
private StrokeCollection DisplayCanvasStrokeBytes(byte[] array) { // 空输入校验,避免异常 if (array == null || array.Length == 0) return new StrokeCollection(); using (var ms = new MemoryStream(array)) { // StrokeCollection原生支持读取Save方法输出的流格式 return new StrokeCollection(ms); } }
读取后直接赋值给画布即可生效:
// 从数据库读取字节数组后调用示例 DrawingCanvas.Strokes = DisplayCanvasStrokeBytes(从数据库读取的笔触字节数组);
额外优化建议
你当前保存背景的逻辑需要清空笔触再渲染,会打断用户当前操作状态,可直接提取背景Brush的数据源序列化,不需要修改画布状态:
private byte[] GetBitMapOfCanvasBackground() { if (DrawingCanvas.Background is not ImageBrush backgroundBrush || backgroundBrush.ImageSource is not BitmapSource bitmapSource) return Array.Empty<byte>(); using var ms = new MemoryStream(); var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); encoder.Save(ms); return ms.ToArray(); }
内容的提问来源于stack exchange,提问作者AnnaJoyW
相关产品推荐
相关产品推荐

