1.应用需求
在实际处理业务逻辑时,往往会要求打开或者保存文件,本章节探讨并测试一些简单的图像文件操作的IO,测试NET上的API。因此第一个DEMO设计一个简单的窗口,实现通过WINDOWS的文件管理界面,将任意的图片加载到窗口中,如下图所示。
在C#中处理图片文件可以使用.NET Framework提供的System.Drawing命名空间,或者使用更现代的.NET Core/.NET 5+中的System.Drawing.Common库。
2.调用API对象分析
OpenFileDialog
是一个用于显示文件选择对话框的类,它允许用户从文件系统中选择文件。在 WPF 应用程序中,你可以使用 OpenFileDialog
来让用户选择一个或多个文件。
(1).定义一个打开文件的会话,如下段代码:
using Microsoft.Win32;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "选择文件";
openFileDialog.InitialDirectory = @"C:\Users\Username\Documents";
openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
openFileDialog.Multiselect = true;
OpenFileDialog
定义在 Microsoft.Win32下,这与WINFROM的System.Windows.Forms 是不同的,在构建WPF的应用程序时应该谨慎选择。
你可以设置一些属性来定制文件选择对话框的外观和行为。以下是一些常用的属性:
Title
:对话框标题。InitialDirectory
:对话框打开时默认显示的文件夹。Filter
:文件过滤器,用于指定允许选择的文件类型。Multiselect
:指示是否允许选择多个文件。
(2).显示会话并判断用户的选择,如下段代码:
if (openFileDialog.ShowDialog() == true)
{
// 用户点击了确定按钮
}
(3).获取选择的文件:
用户选择的文件可以通过 FileName
或 FileNames
属性获取:
FileName
:返回单个文件的路径。FileNames
:返回一个包含所有选择文件路径的字符串数组,仅在Multiselect
属性为true
时有效。
string selectedFilePath = openFileDialog.FileName;
string[] selectedFilePaths = openFileDialog.FileNames;
(4.)注销对象,释放资源(这样做有利于程序内存的优化,也可以不这样做):
openFileDialog.Dispose();
BitmapImage
和 Bitmap
是用于处理图像的两个不同的类,分别用于 WPF中处理图像数据。 与 Bitmap
不同,BitmapImage
可以在非 UI 线程上加载图像,因为它是基于 WPF 图像系统的,它会在后台自动管理图像加载和缓存。BitmapImage
对象是只读的,不能直接修改图像的像素数据。如果你需要对图像进行编辑、处理或绘制,你应该考虑使用 Bitmap
类。
(1).在XAML中定义一个图片,并进行绑定:
<Image Source="{Binding ImageSource}" Stretch="Uniform"/>
(2).给接口中的图像赋值:
BitmapImage bitmapImage = new BitmapImage(new Uri("image.jpg", UriKind.RelativeOrAbsolute));
3.DEMO工程代码:
(1).XML文件:
<UserControl x:Class="ImageProcessDemo.Modules.ModuleName.Views.ViewA"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ImageProcessDemo.Modules.ModuleName.Views"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True" >
<UserControl.Resources>
<!--按键的样式-->
<Style x:Key="tabButton" TargetType="Button" >
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="#9e9bb0"/>
<Setter Property="Height" Value="40"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Margin" Value="2 10"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button" >
<Border Background="{TemplateBinding Background}" CornerRadius="15">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#7163ba"/>
<Setter Property="Foreground" Value="#ffffff"/>
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid Width="400">
<!--定义行列-->
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="500"/>
</Grid.RowDefinitions>
<Grid Grid.Column="0" Grid.Row="0">
<Button Content="Start" Background="#7163ba" Foreground="white" Style="{StaticResource tabButton}" Command="{Binding GetCommand}"/>
</Grid>
<Grid Grid.Column="0" Grid.Row="1">
<Image Source="{Binding ImageSource}" Stretch="Uniform"/>
</Grid>
</Grid>
</UserControl>
(2).ViewModel文件:
using ImageProcessDemo.Core.Mvvm;
using ImageProcessDemo.Services.Interfaces;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
namespace ImageProcessDemo.Modules.ModuleName.ViewModels
{
public class ViewAViewModel : RegionViewModelBase
{
public DelegateCommand GetCommand { get; private set; }
private string _message;
private BitmapImage _imageSource;
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
public ViewAViewModel(IRegionManager regionManager, IMessageService messageService) :
base(regionManager)
{
GetCommand = new DelegateCommand(Get);
Message = messageService.GetMessage();
}
public override void OnNavigatedTo(NavigationContext navigationContext)
{
//do something
}
private void Get()
{
// 显示文件选择对话框
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files (*.jpg; *.jpeg; *.png; *.bmp)|*.jpg; *.jpeg; *.png; *.bmp";
openFileDialog.Title = "Select an Image File";
if (openFileDialog.ShowDialog() == true)
{
string filePath = openFileDialog.FileName;
Console.WriteLine("Selected image file: " + filePath);
// 创建BitmapImage并设置图像源
BitmapImage bitmapImage = new BitmapImage(new Uri(filePath));
ImageSource = bitmapImage;
}
}
public BitmapImage ImageSource
{
get { return _imageSource; }
set
{
_imageSource = value;
RaisePropertyChanged();
}
}
}
}