簡體   English   中英

RenderTargetBitmap 模糊

[英]RenderTargetBitmap is blurry

嗨,我正在使用 PngBitmapEncoder 從 Canvas 在 memory 中創建圖像。

public void CaptureGraphic()
{
    Canvas canvas = new Canvas();
    canvas.SnapsToDevicePixels = true;
    canvas.Height = IMAGEHEIGHT;
    canvas.Width = IMAGEWIDTH;
    Draw(canvas);
    canvas.Arrange(new Rect(0, 0, IMAGEWIDTH, IMAGEHEIGHT));
    member.MemberImage = GetPngFromUIElement(canvas);
}

public static System.Drawing.Image GetPngFromUIElement(Canvas source)
{
    int width = (int)source.ActualWidth;
    int height = (int)source.ActualHeight;

    if (width == 0)
        width = (int)source.Width;
    if (height == 0)
        height = (int)source.Height;


    RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
    bitmap.Render(source);

    PngBitmapEncoder enc = new PngBitmapEncoder();
    enc.Interlace = PngInterlaceOption.Off;
    enc.Frames.Add(BitmapFrame.Create(bitmap));

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    enc.Save(ms);

    System.Drawing.Image image = System.Drawing.Image.FromStream(ms);

    ms.Flush();
    ms.Dispose();

    return image;
}

然后我使用 GDI+ DrawImage() 方法將圖像發送到打印機。 但是打印的結果是模糊的。

我嘗試將原始 canvas 尺寸與打印尺寸相匹配以避免任何縮放,同樣我嘗試使原始尺寸更大,以便縮放后的圖像保持質量,但最終打印的圖像總是模糊。

任何人都可以提供任何建議/替代方案。 我已經設置了相當多的 GDI+ 打印例程,現在還不能選擇轉到 wpf 文檔。

謝謝

我得到了同樣模糊的結果,並提出了以下代碼,它對偏移應用了相同的想法,但是使用了 DrawingVisual 上的 Offset 屬性(因為我使用的是 DrawDrawing,它沒有與偏移參數):

public static Image ToBitmap(Image source)
{
    var dv = new DrawingVisual();
    // Blur workaround
    dv.Offset = new Vector(0.5, 0.5);
    using (var dc = dv.RenderOpen())
        dc.DrawDrawing(((DrawingImage)source.Source).Drawing);

    var bmp = new RenderTargetBitmap((int)source.Width, (int)source.Height, 96, 96, PixelFormats.Pbgra32);
    bmp.Render(dv);

    var bitMapImage = new Image();
    bitMapImage.Source = bmp;
    bitMapImage.Width = source.Width;
    bitMapImage.Height = source.Height;

    return bitMapImage;
}

您正在以 96 DPI 捕獲 bitmap。 不要在 RenderTargetBitmap 的構造函數中使用 96,而是嘗試匹配打印機 output 的 DPI。 或者,您可以進行數學運算並計算寬度/高度的差異,並相應地重新調整報告上的圖像(結果是報告上的圖像會顯得更小)。

我有同樣的問題。 為了避免模糊的文本和線條,我必須在 X 和 Y 方向上以 0.5 的偏移量繪制所有內容。 例如,一條水平線可以是

drawingContext.DrawLine(pen, new Point(10.5,10.5), new Point(100.5,10.5));

就我而言,我在不同的線程中渲染到 RenderTargetBitmap 以提高 UI 性能。 渲染的 bitmap 然后被凍結並使用

drawingContext.DrawImage(bitmap, new Rect(0.5, 0, bitmap.Width, bitmap.Height));

在這里,我需要一個 0.5 的額外偏移量,但(奇怪的是)只在 X 方向上,這樣渲染的圖像就不再看起來模糊了。

想我已經找到了答案。

http://www.charlespetzold.com/blog/2007/12/High-Resolution-Printing-of-WPF-3D-Visuals.html

我只需要隨着 dpi 和 voila 一起放大圖像大小,大大增加了文件大小!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM