将 wpf 图像控件保存到文件的最简单方法 [英] Easiest way of saving wpf Image control to a file

查看:43
本文介绍了将 wpf 图像控件保存到文件的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 wpf 应用程序中有一个 Image 控件,里面有一个大图像,但控件本身只有 60x150,这意味着它只显示该图像的某个部分.将可见部分保存到文件的最简单方法是什么?

I have a Image control inside my wpf application, which has a large image inside of it, but the control itself is only 60x150, this means it only shows a certain portion of this image. What is the easiest way of saving the visible portion to a file?

感谢您的帮助.

我最终使用了在此处找到的代码(在此处发布之前我无法找到)..

I ended up using code found here (which I've not been able to locate before posting here)...

Grid r = new Grid();
        r.Background = new ImageBrush(image2.Source);


    System.Windows.Size sz = new System.Windows.Size(image2.Source.Width, image2.Source.Height);
    r.Measure(sz);
    r.Arrange(new Rect(sz));

    RenderTargetBitmap rtb = new RenderTargetBitmap((int)image2.Source.Width, (int)image2.Source.Height, 96d, 96d, PixelFormats.Default);
    rtb.Render(r);

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

    FileStream fs = File.Open(@"C:\lol.png", FileMode.Create);
    encoder.Save(fs);
    fs.Close();

推荐答案

您可以使用 RenderTargetBitmap 类和 BitmapEncoder.

You could use RenderTargetBitmap class and BitmapEncoder.

定义这些方法:

void SaveToBmp(FrameworkElement visual, string fileName)
{
    var encoder = new BmpBitmapEncoder();
    SaveUsingEncoder(visual, fileName, encoder);
}

void SaveToPng(FrameworkElement visual, string fileName)
{
    var encoder = new PngBitmapEncoder();
    SaveUsingEncoder(visual, fileName, encoder);
}

// and so on for other encoders (if you want)


void SaveUsingEncoder(FrameworkElement visual, string fileName, BitmapEncoder encoder)
{
    RenderTargetBitmap bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
    bitmap.Render(visual);
    BitmapFrame frame = BitmapFrame.Create(bitmap);
    encoder.Frames.Add(frame);

    using (var stream = File.Create(fileName))
    {
        encoder.Save(stream);
    }
}

如果您在这样的容器中拥有 Image 控件:

If you have your Image control inside a container like this:

<Grid x:Name="MyGrid">
    <Image Name="MyImage" Stretch="None"></Image>
</Grid>

你只需要这样做:

SaveToPng(MyGrid, "image.png");

否则,您可以在使用 RenderTargetBitmap 时简单地传递您想要的尺寸:

Otherwise you can simply pass the dimensions you want when you use RenderTargetBitmap:

SaveToPng(MyImage, "image.png");

...

RenderTargetBitmap bitmap = new RenderTargetBitmap(YourWidth, YourHeight, 96, 96, PixelFormats.Pbgra32);

这篇关于将 wpf 图像控件保存到文件的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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