1

在 WPF 应用程序中,做这种事情的最佳方法是什么?如果我有一个 1000 x 1000 大小的网格,我如何将其保存为 200 x 200 大小的图像?

谢谢!

4

1 回答 1

0

稍微修改了我的答案,以便在这种情况下将
大 WPF 画布切成许多小 PNG 图像

像这样称呼它

SaveFrameworkElementToPng(myGrid, 200, 200, "MyImage.png");

SaveFrameworkElementToPng

private void SaveFrameworkElementToPng(FrameworkElement frameworkElement,
                                       int width,
                                       int height,
                                       string filePath)
{
    BitmapImage bitmapImage = VisualToBitmapImage(frameworkElement);
    SaveImage(bitmapImage, width, height, filePath);
}

public BitmapImage VisualToBitmapImage(FrameworkElement frameworkElement)
{
    RenderTargetBitmap rtb = new RenderTargetBitmap((int)frameworkElement.ActualWidth,
                                                    (int)frameworkElement.ActualHeight,
                                                    96d,
                                                    96d,
                                                    PixelFormats.Default);
    rtb.Render(frameworkElement);

    MemoryStream stream = new MemoryStream();
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(rtb));
    encoder.Save(stream);

    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.StreamSource = stream;
    bitmapImage.EndInit();

    return bitmapImage;
}

public void SaveImage(BitmapImage sourceImage,
                        int width,
                        int height,
                        string filePath)
{
    TransformGroup transformGroup = new TransformGroup();
    ScaleTransform scaleTransform = new ScaleTransform();
    scaleTransform.ScaleX = (double)width / sourceImage.PixelWidth;
    scaleTransform.ScaleY = (double)height / sourceImage.PixelHeight;
    transformGroup.Children.Add(scaleTransform);

    DrawingVisual vis = new DrawingVisual();
    DrawingContext cont = vis.RenderOpen();
    cont.PushTransform(transformGroup);
    cont.DrawImage(sourceImage, new Rect(new Size(sourceImage.PixelWidth, sourceImage.PixelHeight)));
    cont.Close();

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

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

    using (FileStream stream = new FileStream(filePath, FileMode.Create))
    {
        encoder.Save(stream);
        stream.Close();
    }
}
于 2012-06-10T14:41:52.447 回答