如何捕获网格到不同大小的图像文件?

时间:2012-06-10 14:08:42

标签: .net wpf c#-4.0

在WPF应用程序中,做这种事情的首选方法是什么? 如果我的网格尺寸为1000 x 1000,如何将其保存为尺寸为200 x 200的图像?

谢谢!

1 个答案:

答案 0 :(得分:0)

稍微修改了我的答案,以便它适用于这种情况
Slice Large WPF Canvas Into Many Small PNG Images

像这样称呼

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();
    }
}