Last active
November 15, 2023 14:40
-
-
Save ZacharyPatten/531fe7a73b244fdadde96cb9e67dfca5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Drawing; | |
Console.WriteLine("Sliding Puzzle Image Crop"); | |
if (!OperatingSystem.IsWindows()) | |
{ | |
Console.WriteLine("This app is only supported on Windows OS."); | |
return; | |
} | |
#pragma warning disable CA1416 | |
int width; | |
Console.Write("How many tiles wide? "); | |
while (!int.TryParse((Console.ReadLine() ?? "").Trim(), out width) || width <= 0) | |
{ | |
Console.WriteLine("Invalid input. Try again..."); | |
Console.Write("How many tiles wide? "); | |
} | |
int height; | |
Console.Write("How many tiles tall? "); | |
while (!int.TryParse((Console.ReadLine() ?? "").Trim(), out height) || height <= 0) | |
{ | |
Console.WriteLine("Invalid input. Try again..."); | |
Console.Write("How many tiles tall? "); | |
} | |
Image? image = null; | |
Console.Write("What is the file path of the image? "); | |
string path = (Console.ReadLine() ?? "").Trim(); | |
try { image = Image.FromFile(path); } | |
catch { /* intentionally blank */ } | |
while (image is null) | |
{ | |
Console.WriteLine("Invalid input. Try again..."); | |
Console.Write("What is the file path of the image? "); | |
path = (Console.ReadLine() ?? "").Trim(); | |
try { image = Image.FromFile(path); } | |
catch { /* intentionally blank */ } | |
} | |
int tileWidth = image.Width / width; | |
int tileHeight = image.Height / height; | |
Bitmap bitmap = new(image); | |
Bitmap[,] tiles = new Bitmap[width, height]; | |
string directory = Path.GetDirectoryName(path) ?? ""; | |
string extension = Path.GetExtension(path) ?? ""; | |
string fileName = Path.GetFileNameWithoutExtension(path) ?? ""; | |
for (int i = 0; i < width; i++) | |
{ | |
for (int j = 0; j < height; j++) | |
{ | |
Rectangle rectangle = new(i * tileWidth, j * tileHeight, tileWidth, tileHeight); | |
tiles[i, j] = bitmap.Clone(rectangle, bitmap.PixelFormat); | |
string tilePath = $"{directory}{Path.DirectorySeparatorChar}{fileName}_{i}_{j}{extension}"; | |
tiles[i, j].Save(tilePath); | |
Console.WriteLine($"{tilePath} saved..."); | |
} | |
} | |
Console.Write("Image Cropping Complete. :)"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment