-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
421 lines (370 loc) · 17.5 KB
/
Program.cs
File metadata and controls
421 lines (370 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
using ImageMagick;
namespace BulkImageConverter
{
internal class Program
{
private static void Main(string[] args)
{
DisplayWelcomeMessage();
while (true)
{
DisplayMainMenu();
string choice = Console.ReadLine().Trim().ToLower();
switch (choice)
{
case "1":
Console.Write("Enter the path of the file or drag and drop the file: ");
string singleFilePath = Console.ReadLine().Trim('"');
ConvertSingleFile(singleFilePath);
break;
case "2":
ConvertMultipleFiles();
break;
case "/help":
DisplayInstructions();
break;
case "/exit":
Console.WriteLine("Exiting program. Goodbye!");
return;
default:
WriteLineWithColor("Invalid option selected. Please try again.", ConsoleColor.Red);
break;
}
}
}
private static void DisplayWelcomeMessage()
{
Console.Clear();
WriteLineWithColor("============================================", ConsoleColor.Magenta);
WriteLineWithColor(" Welcome to Image Converter ", ConsoleColor.Magenta);
WriteLineWithColor("============================================", ConsoleColor.Magenta);
}
private static void DisplayMainMenu()
{
Console.WriteLine("\nMain Menu:");
Console.WriteLine("1. Convert a single image.");
Console.WriteLine("2. Convert multiple images from a directory.");
Console.WriteLine("Type '/help' for instructions or '/exit' to quit.");
Console.Write("Enter your choice: ");
}
private static void ConvertSingleFile(string filePath)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Available image types: webp, png, bmp, tif, gif, jpg, jpeg");
Console.Write("Enter the target image type: ");
string targetType = Console.ReadLine();
Console.Write("Add watermark? (yes/no): ");
string addWatermark = Console.ReadLine().ToLower();
string watermarkPathOrText = null;
Gravity watermarkPosition = Gravity.Center;
if (addWatermark == "yes")
{
int watermarkTypeChoice;
bool isValidChoice = false;
do
{
// Prompt user for watermark type: text or image.
Console.Write("Choose watermark type (1: text, 2: image): ");
if (int.TryParse(Console.ReadLine(), out watermarkTypeChoice))
{
if (watermarkTypeChoice == 1 || watermarkTypeChoice == 2)
{
isValidChoice = true;
}
else
{
Console.WriteLine("Invalid choice. Please enter 1 for text or 2 for an image.");
}
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number (1 or 2).");
}
} while (!isValidChoice);
// Depending on the choice, either get the text or path.
watermarkPathOrText = GetWatermarkPathOrText(watermarkTypeChoice.ToString());
if (watermarkTypeChoice == 2) // Only ask for watermark position if it's an image watermark.
{
// Now, get the watermark position.
watermarkPosition = GetWatermarkPosition();
}
}
Console.Write("Delete original file after conversion? (yes/no): ");
string deleteOriginal = Console.ReadLine().ToLower();
if (deleteOriginal == "yes")
{
Console.Write("Are you sure you want to delete the original file? (yes/no): ");
string confirmDelete = Console.ReadLine().ToLower();
deleteOriginal = confirmDelete;
}
Console.ResetColor();
ConvertImage(filePath, targetType, watermarkPathOrText, deleteOriginal == "yes", watermarkPosition);
}
private static void ConvertImage(string sourceFilePath, string targetFileName, string watermarkPathOrText, bool deleteOriginal, Gravity watermarkPosition = Gravity.Center)
{
try
{
string targetFilePath = Path.Combine(Path.GetDirectoryName(sourceFilePath), targetFileName);
using (MagickImage image = new MagickImage(sourceFilePath))
{
if (!string.IsNullOrEmpty(watermarkPathOrText))
{
// Check if the provided watermark is a text or an image path
if (File.Exists(watermarkPathOrText))
{
using (MagickImage watermark = new MagickImage(watermarkPathOrText))
{
watermark.Evaluate(Channels.Alpha, EvaluateOperator.Divide, 2.0); // Adjusting opacity (optional)
image.Composite(watermark, watermarkPosition, CompositeOperator.Over);
}
}
else // Treat as text watermark
{
MagickReadSettings readSettings = new MagickReadSettings()
{
BackgroundColor = MagickColors.Transparent, // Text background will be transparent
FillColor = MagickColors.White, // Text will be white
FontPointsize = 30, // Font size
Width = image.Width // Width of the text canvas
};
using (MagickImage textWatermark = new MagickImage($"label:{watermarkPathOrText}", readSettings))
{
image.Composite(textWatermark, watermarkPosition, CompositeOperator.Over);
}
}
}
image.Write(targetFilePath);
}
if (deleteOriginal)
{
File.Delete(sourceFilePath);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error converting {sourceFilePath} to {targetFileName}: {ex.Message}");
}
}
static void ConvertMultipleFiles(string rootDirectory = null, string watermarkPath = null)
{
Console.ForegroundColor = ConsoleColor.Blue;
if (string.IsNullOrEmpty(rootDirectory))
{
Console.Write("Enter the directory path or drag and drop the folder: ");
rootDirectory = Console.ReadLine().Trim('"');
}
bool includeSubdirs = false; // Initialize as false
bool renameBasedOnFolder = false; // Initialize as false
Gravity watermarkPosition = Gravity.Center; // Initialize watermark position
int watermarkTypeChoice = 0; // Initialize outside of the if block
bool isValidChoice = false;
do
{
// Prompt user for watermark type: text or image.
Console.Write("Choose watermark type (1: text, 2: image): ");
if (int.TryParse(Console.ReadLine(), out watermarkTypeChoice))
{
if (watermarkTypeChoice == 1 || watermarkTypeChoice == 2)
{
isValidChoice = true;
if (string.IsNullOrEmpty(watermarkPath))
{
Console.Write("Add watermark? (yes/no): ");
string addWatermark = Console.ReadLine().ToLower();
if (addWatermark == "yes")
{
// Depending on the choice, either get the text or path.
watermarkPath = GetWatermarkPathOrText(watermarkTypeChoice.ToString());
if (watermarkTypeChoice == 2) // Only ask for watermark position if it's an image watermark.
{
// Now, get the watermark position.
watermarkPosition = GetWatermarkPosition();
}
}
}
}
else
{
Console.WriteLine("Invalid choice. Please enter 1 for text or 2 for an image.");
}
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number (1 or 2).");
}
} while (!isValidChoice);
Console.Write("Include subdirectories? (yes/no): ");
string includeSubdirsChoice = Console.ReadLine().ToLower();
if (includeSubdirsChoice == "yes")
{
includeSubdirs = true;
}
Console.Write("Rename files based on folder name? (yes/no): ");
string renameBasedOnFolderChoice = Console.ReadLine().ToLower();
if (renameBasedOnFolderChoice == "yes")
{
renameBasedOnFolder = true;
}
List<string> imageExtensions = new List<string> { "webp", "png", "bmp", "tif", "gif", "jpg", "jpeg" };
Console.WriteLine("Available image types: webp, png, bmp, tif, gif, jpg, jpeg");
Console.Write("Enter the source image type: ");
string sourceType = Console.ReadLine();
Console.Write("Enter the target image type: ");
string targetType = Console.ReadLine();
Console.Write("Delete original files after conversion? (yes/no): ");
string deleteOriginal = Console.ReadLine().ToLower();
if (deleteOriginal == "yes")
{
Console.Write("Are you sure you want to delete the original files? (yes/no): ");
string confirmDelete = Console.ReadLine().ToLower();
deleteOriginal = confirmDelete;
}
Console.ResetColor();
if (sourceType == "all")
{
foreach (var extension in imageExtensions)
{
ConvertImagesInDirectory(rootDirectory, extension, targetType, watermarkPath, deleteOriginal == "yes", includeSubdirs, renameBasedOnFolder, watermarkPosition);
}
}
else
{
ConvertImagesInDirectory(rootDirectory, sourceType, targetType, watermarkPath, deleteOriginal == "yes", includeSubdirs, renameBasedOnFolder, watermarkPosition);
}
}
// Now, we also need to adjust the ConvertImagesInDirectory method to accept and process the renaming flag:
private static void ConvertImagesInDirectory(string directoryPath, string sourceType, string targetType, string watermarkPath, bool deleteOriginal, bool includeSubdirs, bool renameBasedOnFolder, Gravity watermarkPosition = Gravity.Center)
{
string[] sourceFiles = Directory.GetFiles(directoryPath, $"*.{sourceType}");
int imageIndex = 1;
foreach (var sourceFile in sourceFiles)
{
string targetFileName;
if (renameBasedOnFolder)
{
string folderName = new DirectoryInfo(directoryPath).Name;
targetFileName = $"{folderName}_{imageIndex}.{targetType}";
}
else
{
targetFileName = $"{Path.GetFileNameWithoutExtension(sourceFile)}.{targetType}";
}
ConvertImage(sourceFile, targetFileName, watermarkPath, deleteOriginal, watermarkPosition);
imageIndex++;
}
if (includeSubdirs)
{
string[] subDirectories = Directory.GetDirectories(directoryPath);
foreach (var subDir in subDirectories)
{
ConvertImagesInDirectory(subDir, sourceType, targetType, watermarkPath, deleteOriginal, includeSubdirs, renameBasedOnFolder, watermarkPosition);
}
}
}
private static string GetWatermarkPathOrText(string watermarkTypeChoice)
{
Console.Write("Enter the watermark path or text: ");
string watermarkPathOrText = Console.ReadLine().Trim('"');
if (watermarkTypeChoice == "1")
{
// This is a text watermark, so return it as is.
return watermarkPathOrText;
}
else if (watermarkTypeChoice == "2")
{
// This is an image watermark, so check if it's a valid file path.
if (File.Exists(watermarkPathOrText))
{
return watermarkPathOrText;
}
else
{
Console.WriteLine("Invalid image watermark path.");
return null;
}
}
else
{
Console.WriteLine("Invalid watermark type choice.");
return null;
}
}
private static Gravity GetWatermarkPosition()
{
Console.WriteLine("Choose watermark position:");
Console.WriteLine("1. Top");
Console.WriteLine("2. Middle");
Console.WriteLine("3. Bottom");
while (true)
{
Console.Write("Enter the position (1/2/3): ");
string positionChoice = Console.ReadLine();
if (positionChoice == "1")
{
return Gravity.North;
}
else if (positionChoice == "2")
{
return Gravity.Center;
}
else if (positionChoice == "3")
{
return Gravity.South;
}
else
{
Console.WriteLine("Invalid choice. Please enter 1, 2, or 3.");
}
}
}
// ... rest of the methods ...
private static string GetInput(string prompt)
{
Console.Write(prompt);
return Console.ReadLine().Trim('"');
}
private static bool GetYesOrNo(string prompt)
{
while (true)
{
string response = GetInput(prompt).Trim().ToLower();
if (response == "yes") return true;
if (response == "no") return false;
WriteLineWithColor("Please answer with 'yes' or 'no'.", ConsoleColor.Red);
}
}
private static string GetInputFromOptions(string prompt, List<string> options)
{
while (true)
{
string response = GetInput(prompt).Trim().ToLower();
if (options.Contains(response))
return response;
WriteLineWithColor($"Please select a valid option from: {string.Join(", ", options)}", ConsoleColor.Red);
}
}
private static void WriteLineWithColor(string message, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ResetColor();
}
private static void DisplayInstructions()
{
Console.Clear();
WriteLineWithColor("============================================", ConsoleColor.Magenta);
WriteLineWithColor(" Instructions ", ConsoleColor.Magenta);
WriteLineWithColor("============================================", ConsoleColor.Magenta);
Console.WriteLine("\n1. When prompted, you can choose to convert either a single image or multiple images from a directory.");
Console.WriteLine("2. For a single image conversion, provide the path for the image you want to convert.");
Console.WriteLine("3. For converting multiple images, you can enter the directory path of the images. You also have an option to include subdirectories.");
Console.WriteLine("4. Specify the target image type (e.g., jpg, png).");
Console.WriteLine("5. Optionally, you can add a watermark to the image(s). If you choose to, you will be prompted for the watermark image path.");
Console.WriteLine("6. Optionally, you can decide to delete the original file(s) after conversion.");
Console.WriteLine("7. The converted image(s) will be saved in the same directory as the original file(s).");
Console.WriteLine("8. At any point, you can type '/exit' to leave the program.");
Console.Write("\nPress ENTER to return to the main menu.");
Console.ReadLine();
}
}
}