/
benjamingotbenz
/
PROJECT
Обзор
Документация
Войти
/
benjamingotbenz
/
PROJECT
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
2
CI/CD
Аналитика
Безопасность
master
ProgramCLI.cs
214 строк
8 KB
benjamingotbenz
Исправлен вылет при некорректном вводе в методе ChoiceCalculatePsnr
24 май 2026, 12:39
24 май 2026, 12:39
02ca787
Код
Авторство
О чём код?
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ProjectLSB { internal class ProgramCLI { static void Main() { GetChoice(); } //Метод для выбора, что дальше делать: Encode/Decode/Exit private static void GetChoice() { while (true) { Console.WriteLine("1 - Встроить сообщение"); Console.WriteLine("2 - Извлечь сообщение"); Console.WriteLine("3 - Посчитать PSNR"); Console.WriteLine("4 - Открыть инструкцию"); Console.WriteLine("0 - Выход"); Console.Write("Выбор: "); string choice = Console.ReadLine(); if (choice == "1") ChoiceEncode(); else if (choice == "2") ChoiceDecode(); else if (choice == "3") ChoiceCalculatePsnr(); else if (choice == "4") ChoiceShowInstruction(); else if (choice == "0") { if (ChoiceExit()) break; } else { Console.Clear(); Console.WriteLine("Некорректный ввод. Попробуйте снова\n"); } } } private static void ChoiceEncode() { try { (string, string) result = CollectInformation(); string pathWhereFileIs = result.Item1; string outputImageFormat = result.Item2; string text = GetMessage(); Console.WriteLine("Подождите..."); CoreLSB.ImageEncode(text, pathWhereFileIs, outputImageFormat); Console.Clear(); Console.WriteLine("Изображение сохранено!\n"); Console.WriteLine("Нажмите любую клавишу, чтобы вернуться в главное меню"); Console.ReadKey(); Console.Clear(); } catch (Exception ex) { Console.Clear(); Console.WriteLine("Ошибка: " + ex.Message); Console.WriteLine("Нажмите любую клавишу, чтобы продолжить..."); Console.ReadKey(); Console.Clear(); } } private static void ChoiceDecode() { try { Console.Write("Введите путь к файлу: "); string pathToFile = GetPath(); string result = CoreLSB.ImageDecode(pathToFile); Console.WriteLine($"Извлеченное сообщение:\n\n{result}\n"); Console.WriteLine("Нажмите любую клавишу, чтобы вернуться в главное меню"); Console.ReadKey(); Console.Clear(); } catch (Exception ex) { Console.Clear(); Console.WriteLine("Ошибка: " + ex.Message); Console.WriteLine("Нажмите любую клавишу, чтобы продолжить..."); Console.ReadKey(); Console.Clear(); } } private static void ChoiceCalculatePsnr() { try { Console.Write("Введите путь до неизмененного изображения: "); string originalPath = GetPath(); Console.Write("\nВведите путь до измененного изображения: "); string modifiedPath = GetPath(); double psnr = PSNR.CalculatePSNR(originalPath, modifiedPath); if (psnr == double.PositiveInfinity) { Console.WriteLine("\nИзображения одинаковые!\n"); } else { Console.WriteLine($"PSNR: {psnr}"); } Console.Write("Нажмите любую клавишу, чтобы продолжить..."); Console.ReadKey(); Console.Clear(); } catch (Exception ex) { Console.Clear(); Console.WriteLine("Ошибка: " + ex.Message); Console.WriteLine("Нажмите любую клавишу, чтобы продолжить..."); Console.ReadKey(); Console.Clear(); } } private static void ChoiceShowInstruction() { Console.WriteLine("Working on it"); } private static bool ChoiceExit() { while (true) { Console.WriteLine("Вы уверены?"); Console.WriteLine("1 - Да, 2 - Отмена"); Console.Write("Выбор: "); string confirm = Console.ReadLine(); if (confirm == "1") return true; if (confirm == "2") { Console.Clear(); return false; } Console.Clear(); Console.WriteLine("Некорректный ввод. Попробуйте снова\n"); } } //Метод получает текст, который пользователь хочет встроить в изображения private static string GetMessage() { while (true) { Console.WriteLine("Введите текст (пустая строка - конец ввода): "); List<string> lines = new(); while (true) { string line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) break; lines.Add(line); } string text = string.Join("\n", lines); if (!string.IsNullOrEmpty(text)) { return text; } Console.Clear(); Console.WriteLine("Сообщение не может быть пустым. Попробуйте снова\n"); } } // В методе собираются данные, куда и как сохранять файл private static (string path, string format) CollectInformation() { // Куда сохранить Console.WriteLine("Введите путь к файлу (учитывайте, что итоговое изображение будет сохранено в той же папке): "); string pathWhereFileIs = GetPath(); // Как сохранить string outputImageFormat; while (true) { Console.WriteLine("Как сохранить:\n1 - в jpg(Корректность встроенного сообщения не гарантируется)\n2 - png"); Console.Write("Выбор: "); outputImageFormat = Console.ReadLine(); if (outputImageFormat != "1" && outputImageFormat != "2") { Console.Clear(); Console.WriteLine("Некорректный ввод. Попробуйте снова\n"); } else break; } return (pathWhereFileIs, outputImageFormat); } //В методе автоматически убираются лишние символы, которые Windows добавляет при вводе через CMD //Также, тут есть проверки private static string GetPath() { string path = Console.ReadLine(); if (string.IsNullOrWhiteSpace(path)) throw new Exception("Путь до изображения пустой"); path = path.Trim().Trim('"'); if (!File.Exists(path)) throw new Exception("Файл не найден!"); return Path.GetFullPath(path); } } }