将 PNG 文件导入 Wpf Canvas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16892116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Import a PNG file into Wpf Canvas
提问by Vivek Saurav
So, I have imported the canvas into a png file.
所以, I have imported the canvas into a png file.
The code for saving the canvas is:
保存画布的代码是:
private void CommandBinding_Executed(object sender, RoutedEventArgs e)
{
Rect rect = new Rect(canvas1.RenderSize);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right,
(int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default);
rtb.Render(canvas1);
//endcode as PNG
Microsoft.Win32.SaveFileDialog dl1 = new Microsoft.Win32.SaveFileDialog();
dl1.FileName = "Sample Image";
dl1.DefaultExt = ".png";
dl1.Filter = "Image documents (.png)|*.png";
Nullable<bool> result = dl1.ShowDialog();
if (result == true)
{
string filename = dl1.FileName;
BitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
//save to memory stream
System.IO.MemoryStream ms = new System.IO.MemoryStream();
pngEncoder.Save(ms);
ms.Close();
System.IO.File.WriteAllBytes(filename, ms.ToArray());
Console.WriteLine("Done");
}
}
Now I want to import an image (png file) back to canvas in my application,
现在 I want to import an image (png file) back to canvas in my application,
i.e. to open a png image into a WPF canvas.
即打开一个 png 图像到 WPF 画布中。
So kindly dump the c#code which can import any image file into the canvas in WPF.
所以请转储c#可以将任何图像文件导入到 WPF 画布中的代码。
回答by Krishna
I believe this is what you are looking for?
我相信这就是你要找的?
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@"mypictures\savedimage.png", UriKind.Relative));
canvas.Background = brush;
回答by Vivek Saurav
Thanks to Krishna, the best solution will be:
感谢 Krishna,最好的解决方案是:
private void Open_Image(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dl1 = new Microsoft.Win32.OpenFileDialog();
dl1.FileName = "MYFileSave";
dl1.DefaultExt = ".png";
dl1.Filter = "Image documents (.png)|*.png";
Nullable<bool> result = dl1.ShowDialog();
if (result == true)
{
string filename = dl1.FileName;
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri(@filename, UriKind.Relative));
canvas1.Background = brush;
}
}

