Загрузка данных
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;
using SkiaSharp;
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();
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)}";
if ((inputExt == ".docx" || inputExt == ".pptx" || inputExt == ".pdf") && (targetExt == ".jpg" || targetExt == ".png"))
{
await Task.Run(() => ConvertDocToImages(file, savePath, targetExt));
}
else
{
await ProcessGeneralFile(file, savePath, targetExt, inputExt);
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка в {Path.GetFileName(file)}: {ex.Message}");
}
progressBar.Value++;
}
lblStatus.Text = "Готово!";
btnStart.Enabled = true;
}
private void ConvertDocToImages(string inputFile, string outFolder, string format)
{
string ext = Path.GetExtension(inputFile).ToLower();
string baseName = Path.GetFileNameWithoutExtension(inputFile);
if (ext == ".docx")
{
Document doc = new Document();
doc.LoadFromFile(inputFile);
for (int i = 0; i < doc.PageCount; i++)
{
object result = doc.SaveToImages(i, Spire.Doc.Documents.ImageType.Bitmap);
SaveUniversal(result, Path.Combine(outFolder, $"{baseName}_p{i + 1}{format}"));
}
}
else if (ext == ".pptx")
{
Presentation ppt = new Presentation();
ppt.LoadFromFile(inputFile);
for (int i = 0; i < ppt.Slides.Count; i++)
{
object result = ppt.Slides[i].SaveAsImage();
SaveUniversal(result, Path.Combine(outFolder, $"{baseName}_s{i + 1}{format}"));
}
}
else if (ext == ".pdf")
{
using (var images = new MagickImageCollection())
{
images.Read(inputFile);
for (int i = 0; i < images.Count; i++)
{
images[i].Write(Path.Combine(outFolder, $"{baseName}_p{i + 1}{format}"));
}
}
}
}
// УНИВЕРСАЛЬНЫЙ МЕТОД СОХРАНЕНИЯ
private void SaveUniversal(object source, string fullPath)
{
// 1. Если это уже поток (Stream)
if (source is Stream stream)
{
using (stream)
using (var image = new MagickImage(stream))
{
image.Write(fullPath);
}
}
// 2. Если это картинка SkiaSharp (SKImage)
else if (source is SKImage skiaImg)
{
using (skiaImg)
using (var data = skiaImg.Encode(SKEncodedImageFormat.Png, 100))
using (var ms = new MemoryStream())
{
data.SaveTo(ms);
ms.Position = 0;
using (var image = new MagickImage(ms))
{
image.Write(fullPath);
}
}
}
}
private async Task ProcessGeneralFile(string file, string savePath, string targetExt, string inputExt)
{
string outPath = Path.Combine(savePath, Path.GetFileNameWithoutExtension(file) + "_conv" + targetExt);
if (_categories["Image"].Contains(inputExt.Replace(".", "")) && 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();
}
}
}
}