在C#中实现图片分割,通常可以使用System.Drawing命名空间下的Bitmap类和Graphics类来处理图像,以下是一个简单的示例代码,演示了如何将一张图片分割成多个小块:
using System; using System.Drawing; using System.IO;
public static void SplitImage(string inputImagePath, string outputFolderPath, int rows, int cols) { // 加载原始图片 Bitmap originalImage = new Bitmap(inputImagePath); int width = originalImage.Width; int height = originalImage.Height; int cropWidth = width / cols; int cropHeight = height / rows; // 确保输出文件夹存在 if (!Directory.Exists(outputFolderPath)) { Directory.CreateDirectory(outputFolderPath); } // 遍历每一行和每一列,裁剪并保存图片 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int x = j * cropWidth; int y = i * cropHeight; Rectangle rect = new Rectangle(x, y, cropWidth, cropHeight); Bitmap croppedImage = originalImage.Clone(rect, originalImage.PixelFormat); // 构建输出文件路径 string outputFilePath = Path.Combine(outputFolderPath, $"part_{i}_{j}.jpg"); croppedImage.Save(outputFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); croppedImage.Dispose(); // 释放资源 } } // 释放原始图片资源 originalImage.Dispose(); }
class Program { static void Main(string[] args) { string inputImagePath = "path_to_your_image.jpg"; // 替换为你的图片路径 string outputFolderPath = "path_to_output_folder"; // 替换为你的输出文件夹路径 int rows = 4; // 设置行数 int cols = 4; // 设置列数 SplitImage(inputImagePath, outputFolderPath, rows, cols); Console.WriteLine("图片分割完成!"); } }
这段代码首先定义了一个SplitImage
方法,该方法接受输入图片路径、输出文件夹路径、行数和列数作为参数,它加载原始图片,计算每个小块的宽度和高度,并遍历每一行和每一列,裁剪出相应的小块并保存到输出文件夹中,在Main
方法中调用SplitImage
方法进行测试。
代码中的path_to_your_image.jpg
和path_to_output_folder
需要替换为你实际的图片路径和输出文件夹路径,确保你有足够的权限来读取和写入这些路径。