写一个简单的图片格式转换器

1、使用ImageMagick
安装magick.net-q16-anycpu.14.6.0
2、前端xaml代码

 <Grid>
     <Grid.RowDefinitions>
         <RowDefinition />
         <RowDefinition Height="40" />
     </Grid.RowDefinitions>

     <Grid>
         <Grid.ColumnDefinitions>
             <ColumnDefinition />
             <ColumnDefinition />
         </Grid.ColumnDefinitions>
         <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
             <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Orientation="Horizontal" Margin="5">
                 <TextBlock Text="当前格式:" FontSize="16" Height="30" />
                 <TextBox Text="{Binding CurrentImageFormat}" Width="100" Height="30" Margin="5" TextAlignment="Center" VerticalContentAlignment="Center" FontSize="14" />
             </StackPanel>
             <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Orientation="Horizontal" Margin="5">
                 <TextBlock Text="转换格式:" FontSize="16" Height="30" />
                 <ComboBox ItemsSource="{Binding FullImageFormat}" SelectedItem="{Binding OutImageFormat}" Width="100" Height="30" Margin="5" FontSize="14" />
             </StackPanel>
         </StackPanel>
         <Border BorderThickness="1" BorderBrush="Gray" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center">
             <Image Width="200" Height="200" Source="{Binding ImageFilePath,Converter={StaticResource converImage},Mode=OneWay}" Stretch="UniformToFill" />
         </Border>
     </Grid>

     <StackPanel Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
         <Button Command="{Binding OpenPhotoFileCommand}" Width="200" Height="30" Content="打开文件" Margin="5" />
         <Button Command="{Binding ConverFormatCommand}" Width="200" Height="30" Content="格式转换" Margin="5" />
     </StackPanel>
 </Grid>

界面打开为
image

3、打开指定文件并选择转换格式
image

4、后台代码

public class MainWindowViewModel : BindableBase
{
    public ICommand OpenPhotoFileCommand { get; set; }
    public ICommand ConverFormatCommand { get; set; }
    private string _imageFilePath;

    public string ImageFilePath
    {
        get => _imageFilePath;
        set => SetProperty(ref _imageFilePath, value);
    }

    private string _currentImageFormat;

    public string CurrentImageFormat
    {
        get => _currentImageFormat;
        set => SetProperty(ref _currentImageFormat, value);
    }

    private string _outImageFormat;

    public string OutImageFormat
    {
        get => _outImageFormat;
        set => SetProperty(ref _outImageFormat, value);
    }

    private string[] _fullImageFormat;

    public string[] FullImageFormat
    {
        get => _fullImageFormat;
        set => SetProperty(ref _fullImageFormat, value);
    }

    public MainWindowViewModel()
    {
        //转换格式写死
        FullImageFormat = new string[]
        {
            "png","jpg","jpeg","jfif","gif","bmp","tif","webp","ico","psd"
        };
        OpenPhotoFileCommand = new DelegateCommand(ExecuteOpen);
        ConverFormatCommand = new DelegateCommand(ExecuteConverter);
    }

    private void ExecuteConverter()
    {
        try
        {
            // 检查输入文件是否存在
            if (!File.Exists(ImageFilePath))
            {
                MessageBox.Show("输入的文件不存在!");
                return;
            }

            // 输出JPG和PNG文件路径
            string outputJpgPath = Path.ChangeExtension(ImageFilePath, OutImageFormat);

            // 初始化MagickImage对象
            using (MagickImage image = new MagickImage(ImageFilePath))
            {
                MagickFormat MagickFormat = GetMagickFormat(CurrentImageFormat.Replace(".", ""));  //去掉小数点
                image.Write(outputJpgPath, MagickFormat);
            }
            MessageBox.Show("转换完成!");
            //打开文件地址
            OpenFileExplorer(ImageFilePath);
        }
        catch (Exception ex)
        {
            MessageBox.Show("转换失败!");
        }
    }

    private void ExecuteOpen()
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "All Files|*.*"; // 设置文件过滤器,这里表示所有文件

        // 用户点击确定后执行以下代码
        if (ofd.ShowDialog() == true)
        {
            ImageFilePath = ofd.FileName; // 获取用户选择的文件的完整路径
            CurrentImageFormat = GetLocalImageFormat();
            try
            {
                MessageBox.Show("文件加载成功。");
            }
            catch (Exception ex)
            {
                // 如果发生异常,弹出消息框显示错误信息
                MessageBox.Show("加载文件时发生错误: " + ex.Message);
            }
        }
        else
        {
            // 如果用户没有选择文件,点击了取消按钮
            MessageBox.Show("操作已取消。");
        }
    }

    public void OpenFileExplorer(string imagePath)
    {
        string folderPath = System.IO.Path.GetDirectoryName(imagePath);
        // 验证路径是否存在
        if (System.IO.Directory.Exists(folderPath))
        {
            try
            {
                // 使用 explorer.exe 打开文件夹
                Process.Start(new ProcessStartInfo
                {
                    FileName = folderPath,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                // 处理启动文件资源管理器时可能出现的异常
                MessageBox.Show($"无法打开文件夹: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        else
        {
            MessageBox.Show("指定的文件夹路径不存在!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    public string GetLocalImageFormat()
    {
        var result = string.Empty;
        if (ImageFilePath == null)
        {
            MessageBox.Show("没有正确打开文件");
        }
        result = Path.GetExtension(ImageFilePath);
        //去掉文件名后缀的小数点
        //result=result.Replace(".", "");
        return result;
    }

    public static MagickFormat GetMagickFormat(string format)
    {
        if (Enum.TryParse(format, true, out MagickFormat result))
        {
            return result;
        }
        else
        {
            throw new ArgumentException($"Unsupported image format: {format}");
        }
    }
}

代码地址

https://github.com/guchen66/ImageFormatConverter
posted @ 2025-04-05 21:37  孤沉  阅读(32)  评论(0)    收藏  举报