Загрузка данных
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using ImageMagick;
using FFMpegCore;
using Spire.Doc;
using Spire.Presentation;
namespace UniversalConverter
{
public partial class Form1 : Form
{
private string[] _selectedFiles;
private readonly Dictionary<string, List<string>> _categories = new Dictionary<string, List<string>>
{
["Image"] = new List<string> { "jpg", "png", "webp", "avif", "bmp", "pdf", "docx", "pptx" },
["Audio"] = new List<string> { "mp3", "wav", "flac", "aac" },
["Video"] = new List<string> { "mp4", "mkv", "mov", "avi" }
};
public Form1()
{
InitializeComponent();
// --- ПОРТАТИВНЫЕ НАСТРОЙКИ ---
// Указываем Magick.NET искать Ghostscript (gsdll64.dll) в папке с программой
MagickNET.SetGhostscriptDirectory(AppDomain.CurrentDomain.BaseDirectory);
// Указываем FFMpegCore искать ffmpeg.exe в папке с программой
GlobalFFOptions.Configure(options => options.BinaryFolder = AppDomain.CurrentDomain.BaseDirectory);
cmbTargetFormat.Items.AddRange(new object[] { "jpg", "png", "pdf", "mp3", "mp4" });
cmbTargetFormat.SelectedIndex = 0;
}
private void btnSelect_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog { Multiselect = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
_selectedFiles = ofd.FileNames;
lstFiles.Items.Clear();
lstFiles.Items.AddRange(_selectedFiles.Select(Path.GetFileName).ToArray());
}
}
}
private async void btnStart_Click(object sender, EventArgs e)
{
if (_selectedFiles == null || _selectedFiles.Length == 0) return;
string savePath = "";
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK) savePath = fbd.SelectedPath;
else return;
}
btnStart.Enabled = false;
string targetExt = "." + cmbTargetFormat.SelectedItem.ToString();
progressBar.Maximum = _selectedFiles.Length;
progressBar.Value = 0;
foreach (var file in _selectedFiles)
{
try
{
string inputExt = Path.GetExtension(file).ToLower();
lblStatus.Text = $"Обработка: {Path.GetFileName(file)}";
// Умная конвертация через PDF (стабильный метод)
if ((inputExt == ".docx" || inputExt == ".pptx" || inputExt == ".pdf") && (targetExt == ".jpg" || targetExt == ".png"))
{
await Task.Run(() => ConvertToImagesViaPdf(file, savePath, targetExt));
}
else
{
await ProcessGeneralFile(file, savePath, targetExt, inputExt);
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}");
}
progressBar.Value++;
}
lblStatus.Text = "Готово!";
btnStart.Enabled = true;
}
private void ConvertToImagesViaPdf(string inputFile, string outFolder, string targetExt)
{
string ext = Path.GetExtension(inputFile).ToLower();
string baseName = Path.GetFileNameWithoutExtension(inputFile);
string pdfPath = inputFile;
bool isTempPdf = false;
if (ext == ".docx")
{
pdfPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".pdf");
Document doc = new Document();
doc.LoadFromFile(inputFile);
doc.SaveToFile(pdfPath, Spire.Doc.FileFormat.PDF);
isTempPdf = true;
}
else if (ext == ".pptx")
{
pdfPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".pdf");
Presentation ppt = new Presentation();
ppt.LoadFromFile(inputFile);
ppt.SaveToFile(pdfPath, Spire.Presentation.FileFormat.PDF);
isTempPdf = true;
}
try
{
// Используем высокую плотность пикселей для четкости текста
var settings = new MagickReadSettings { Density = new Density(300, 300) };
using (var images = new MagickImageCollection())
{
images.Read(pdfPath, settings);
for (int i = 0; i < images.Count; i++)
{
string name = $"{baseName}_page_{i + 1}{targetExt}";
images[i].Write(Path.Combine(outFolder, name));
}
}
}
finally
{
if (isTempPdf && File.Exists(pdfPath)) File.Delete(pdfPath);
}
}
private async Task ProcessGeneralFile(string file, string savePath, string targetExt, string inputExt)
{
string outPath = Path.Combine(savePath, Path.GetFileNameWithoutExtension(file) + "_converted" + targetExt);
// Если это обычная картинка
if (_categories["Image"].Contains(inputExt.TrimStart('.')) && inputExt != ".pdf" && inputExt != ".docx" && inputExt != ".pptx")
{
await Task.Run(() => {
using (var img = new MagickImage(file)) img.Write(outPath);
});
}
else // Аудио и видео
{
await FFMpegArguments.FromFileInput(file).OutputToFile(outPath).ProcessAsynchronously();
}
}
}
}