You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中去除图像周围的外部空白区域?

C#实现图像去外部空白+裁剪旋转的方案

要实现你要的功能,可以用.NET里的ImageSharp(跨平台友好,适合新版.NET)或者System.Drawing.Common(Windows用着顺手)来做,下面给你具体步骤和代码:

核心步骤

  • 定位边界:遍历图像像素,找到黑边框的外边缘,确定需要保留的图像区域
  • 裁剪空白:剪掉外部的空白部分
  • 转正图像:将旋转的图像调整为规整矩形
  • 调整尺寸:缩放至目标的800x1200像素

代码示例(使用ImageSharp)

首先安装NuGet包:SixLabors.ImageSharp

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

public class ImageProcessor
{
    // 调整这个值适配你的黑边框,数值越小越严格识别纯黑像素
    private const int BlackLimit = 30;

    public static void ProcessImage(string inputPath, string outputPath, int targetWidth = 800, int targetHeight = 1200)
    {
        using (Image<Rgb24> image = Image.Load<Rgb24>(inputPath))
        {
            // 1. 确定裁剪范围
            Rectangle cropArea = GetCropBoundary(image);

            // 2. 裁剪外部空白
            image.Mutate(x => x.Crop(cropArea));

            // 3. 旋转转正(根据你的示例图,这里旋转270度,可根据实际情况修改,后续可扩展自动角度检测)
            image.Mutate(x => x.Rotate(RotateMode.Rotate270));

            // 4. 缩放至目标尺寸
            image.Mutate(x => x.Resize(targetWidth, targetHeight));

            // 保存处理后的图像
            image.Save(outputPath);
        }
    }

    private static Rectangle GetCropBoundary(Image<Rgb24> image)
    {
        int top = image.Height;
        int bottom = 0;
        int left = image.Width;
        int right = 0;

        // 遍历所有像素,定位黑边框的边界
        for (int y = 0; y < image.Height; y++)
        {
            for (int x = 0; x < image.Width; x++)
            {
                Rgb24 pixel = image[x, y];
                bool isBlack = pixel.R < BlackLimit && pixel.G < BlackLimit && pixel.B < BlackLimit;
                if (isBlack)
                {
                    if (y < top) top = y;
                    if (y > bottom) bottom = y;
                    if (x < left) left = x;
                    if (x > right) right = x;
                }
            }
        }

        // 留出少量余量,避免误裁内容
        int padding = 2;
        top = Math.Max(0, top - padding);
        bottom = Math.Min(image.Height - 1, bottom + padding);
        left = Math.Max(0, left - padding);
        right = Math.Min(image.Width - 1, right + padding);

        return new Rectangle(left, top, right - left + 1, bottom - top + 1);
    }
}

// 使用示例
// ImageProcessor.ProcessImage("输入图片路径.jpg", "输出图片路径.jpg");

关键说明

  • 黑边框识别:如果你的黑边框不是纯黑,可以调整BlackLimit的数值,数值越大,越接近灰色的像素会被判定为黑边框
  • 旋转自动检测:如果需要自动判断图像旋转角度,可以实现霍夫变换算法,新手可以先手动指定旋转角度,熟悉后再扩展自动检测逻辑
  • 跨平台兼容:ImageSharp支持Windows、Linux、macOS全平台;如果使用.NET Framework,可替换为System.Drawing.Common的API,核心逻辑一致

内容的提问来源于stack exchange,提问作者Imtiaz Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:50:29