C#WPF上传并将图像保存到文件

时间:2018-07-16 15:47:53

标签: c# wpf

我有一个C#WPF应用程序,我希望能够上载图像并将其保存到文件夹。我在下面有以下代码,但不确定在上传并显示图像后如何保存。

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Image Margin="12,12,16,71" Name="imgPhoto" Stretch="Fill" Grid.Column="1"/>
    <Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,34" Name="btnLoad" VerticalAlignment="Bottom" Width="75" Grid.Column="1" Click="btnLoad_Click">
        _Load
    </Button>
    <Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,34" Name="btnSave" VerticalAlignment="Bottom" Width="75" Grid.Column="2" Click="btnSave_Click">
        _Save
    </Button>
</Grid>



private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog fd = new OpenFileDialog();
        if (fd.ShowDialog() == true)
        {
            imgPhoto.Source = new BitmapImage(new Uri(fd.FileName));
            Stream stream = File.OpenRead(fd.FileName);
            stream = File.OpenRead(fd.FileName);
            byte[] binaryImage = new byte[stream.Length];
            stream.Read(binaryImage, 0, (int)stream.Length);
        }
    }

1 个答案:

答案 0 :(得分:1)

要显示已加载文件中的图片

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog fd = new OpenFileDialog();
        if (fd.ShowDialog() == true)
        {
            imgPhoto.Source = new BitmapImage(new Uri(fd.FileName));    
        }
    }

要保存已加载的文件,只需将其复制

    var fileNameToSave = DateTime.Now.ToFileNameFormat() + Path.GetExtension(fd.FileName);
    var imagePath = Path.Combine("C:\" + fileNameToSave);                
    File.Copy(fd.FileName, imagePath);