Saving DrawingVisual to an image file with a given DPI

后端 未结 3 526
感情败类
感情败类 2021-01-27 03:04

I have got a WPF application, and I would like to save a Canvas to a file with a correct DPI value. The Canvas size is the real physical size, eg. 20x10 cm, at 300 DPI, so it\'s

3条回答
  •  故里飘歌
    2021-01-27 03:37

    The following method saves a UIElement to a JPEG file with the specified DPI value:

    public static void SaveElement(UIElement element, double dpi, string path)
    {
        var visual = new DrawingVisual();
        var width = element.RenderSize.Width;
        var height = element.RenderSize.Height;
    
        using (var context = visual.RenderOpen())
        {
            context.DrawRectangle(new VisualBrush(element), null,
                new Rect(0, 0, width, height));
        }
    
        var bitmap = new RenderTargetBitmap(
            (int)(width * dpi / 96), (int)(height * dpi / 96),
            dpi, dpi, PixelFormats.Default);
        bitmap.Render(visual);
    
        var encocer = new JpegBitmapEncoder();
        encocer.Frames.Add(BitmapFrame.Create(bitmap));
    
        using (var stream = File.OpenWrite(path))
        {
            encocer.Save(stream);
        }
    }
    

    Alternatively, apply the DPI scaling to the DrawingVisual:

    public static void SaveElement(UIElement element, double dpi, string path)
    {
        var visual = new DrawingVisual();
        var width = element.RenderSize.Width;
        var height = element.RenderSize.Height;
    
        using (var context = visual.RenderOpen())
        {
            context.DrawRectangle(new VisualBrush(element), null,
                new Rect(0, 0, width / dpi * 96, height / dpi * 96));
        }
    
        var bitmap = new RenderTargetBitmap(
            (int)width, (int)height, dpi, dpi, PixelFormats.Default);
        bitmap.Render(visual);
    
        var encocer = new JpegBitmapEncoder();
        encocer.Frames.Add(BitmapFrame.Create(bitmap));
    
        using (var stream = File.OpenWrite(path))
        {
            encocer.Save(stream);
        }
    }
    

提交回复
热议问题