-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
102 lines (89 loc) · 3.54 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ImageMagick;
using LanguageExt;
namespace PhotoVerticalSplit
{
public class Program
{
public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPEG", ".TIF", ".TIFF", ".BMP", ".GIF", ".PNG" };
public static void Main(string[] args)
{
var poKitchen = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\PoKitchen";
Directory.CreateDirectory(poKitchen);
Console.WriteLine($"Folder po now going to: {poKitchen}");
GetOnlyOneImageInFolder(poKitchen).Match<Unit>(
None: () =>
{
Console.WriteLine("Po: I have no image to slice in this folder!");
return Unit.Default;
},
Some: inputPath =>
{
SliceImage(inputPath);
return Unit.Default;
}
);
Console.WriteLine("Po: I finished slicing! :*");
Console.WriteLine("press enter to exit...");
Console.Read();
}
private static void SliceImage(string inputPath)
{
var originalFileDir = Path.GetDirectoryName(inputPath);
var originalFileName = Path.GetFileNameWithoutExtension(inputPath);
var originalFileExt = Path.GetExtension(inputPath);
using (var image = new MagickImage(inputPath))
{
int i = 0;
var bestImageHeight = GetBestImageHeight(image);
var outputDir = $"{originalFileDir}\\PoOutput";
EmptyOutputDirectory(outputDir);
foreach (MagickImage tile in image.CropToTiles(image.Width, bestImageHeight))
{
tile.Write($"{outputDir}\\{originalFileName}_{i++}.jpg");
}
}
}
private static Option<string> GetOnlyOneImageInFolder(string kitchenDir)
{
var filesInCurrentDir = Directory.GetFiles(kitchenDir).ToList();
var file = filesInCurrentDir.FirstOrDefault(filePath =>
{
return ImageExtensions.Contains(Path.GetExtension(filePath).ToUpperInvariant());
});
return file;
}
private static void EmptyOutputDirectory(string outputDir)
{
Directory.CreateDirectory(outputDir);
string[] filePaths = Directory.GetFiles(outputDir);
foreach (string filePath in filePaths)
File.Delete(filePath);
}
private static int GetBestImageHeight(MagickImage image)
{
var notBadExpectedHeight = 0;
var maxHitTimes = 10;
for (var expectedHeight = image.Width * 4 / 3; expectedHeight >= image.Width; expectedHeight -= 1)
{
var testingImageNumSplitted = image.Height / expectedHeight;
if (image.Height - testingImageNumSplitted * expectedHeight == 0)
{
return expectedHeight;
}
if (image.Height - testingImageNumSplitted * expectedHeight > expectedHeight / 1.5)
{
notBadExpectedHeight = expectedHeight;
if (maxHitTimes-- < 0)
{
break;
}
}
}
return notBadExpectedHeight == 0 ? image.Height : notBadExpectedHeight;
}
}
}