将InkCanvas保存到字节数组到文件时图像被扭曲 [英] Image gets mangled when saving InkCanvas to byte array to file

查看:95
本文介绍了将InkCanvas保存到字节数组到文件时图像被扭曲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用InkCanvas的WPF应用程序.渲染位图时,将其保存到内存流中,将生成的字节写入文件,然后在画图中打开该文件,则图像将被扭曲.知道我在这里可能做错了什么吗?尝试了在SO和codeproject上找到的几种解决方案.很明显,它正在捕获InkCanvas的一部分,但其中大部分是黑色的(我假定为空字节).

I have a WPF application using InkCanvas. When I render the bitmap, save to a memory stream, write the resulting bytes to a file, and then open that file in paint, the image is mangled. Any idea what I may be doing wrong here? Tried several solutions found here on SO and also on codeproject. It's pretty clear that it's capturing part of the InkCanvas but the majority of it is black (I assume null bytes).

也尝试了有/无边距.这是我尝试过的其他链接:

also tried with/without margin. Here are the other links I've tried:

https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/ef71237c-5dfb-4d6c-a402-e8cb02b74e99/如何将墨水笔画转换为位图或字节数组?forum = wpf

将InkCanvas描边转换为字节数组然后返回再次

InkCanvas加载/保存操作

http://www.centrolutions.com/Blog/post/2008/12/09/Convert-WPF-InkCanvas-to-Bitmap.aspx

https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/ba4dc89f-0169-43a9-8374-68e1fb34a222/saving-inkcanvas-as-image?forum=wpf

我需要生成的文件为位图/PNG,以便可以在另一台计算机上查看.

I need the resultant file to be a bitmap/PNG so it can be viewed on another machine.

private byte[] ConvertInkCanvasToByteArray()
{ 
    int margin = (int)this.icSignature.Margin.Left;
    int width = (int)this.icSignature.ActualWidth - margin;
    int height = (int)this.icSignature.ActualHeight - margin;

    RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default);
    rtb.Render(icSignature);

    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(rtb));
    byte[] bitmapBytes;
    using (MemoryStream ms = new MemoryStream())
    {
        encoder.Save(ms); 
        ms.Position = 0;
        bitmapBytes = ms.ToArray();
    }
    return bitmapBytes;
}

从InkCanvas中:

From the InkCanvas:

然后重整:

推荐答案

为避免InkCanvas的页边距出现任何问题,可以将其绘制到中间的DrawingVisual中:

To avoid any problem with the InkCanvas' Margin, you could draw it into an intermediate DrawingVisual:

private byte[] ConvertInkCanvasToByteArray()
{
    var rect = new Rect(icSignature.RenderSize);
    var visual = new DrawingVisual();

    using (var dc = visual.RenderOpen())
    {
        dc.DrawRectangle(new VisualBrush(icSignature), null, rect);
    }

    var rtb = new RenderTargetBitmap(
        (int)rect.Width, (int)rect.Height, 96d, 96d, PixelFormats.Default);
    rtb.Render(visual);

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

    using (var stream = new MemoryStream())
    {
        encoder.Save(stream);
        return stream.ToArray();
    }
}

这篇关于将InkCanvas保存到字节数组到文件时图像被扭曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆