我正在寻找一种从 c# 托管 GDI+ 库中检测 c# 位图边缘空白的解决方案。
图片要么是透明的,要么是白色的,大多数 400 倍的图片是 8000x8000 像素,边缘有大约 2000 像素的空白。
找出边缘、x、y、高度和宽度坐标的最有效方法是什么?我尝试逐个像素地运行,但发现它非常慢。
解决方案更新—— 添加了左/右/上/下边界
图像细节中心图像的问题,现在裁剪任何透明 (0%) 或白色 (#FFFFFF) 像素。
var top = bitmap.Height;
var left = bitmap.Width;
var right = 0;
var bottom = 0;
...
var pData = pData0 + (y * data.Stride) + (x * 4);
var xyAlpha = pData[3];
var xyBlue = pData[0];
var xyGreen = pData[1];
var xyRed = pData[2];
if ((xyAlpha > 0) || (xyRed != 255 && xyGreen != 255 && xyBlue != 255)) {
if (y < top)
top = y;
if (y > bottom)
bottom = y;
if (x < left)
left = x;
if (x > right)
right = x;
}
...
var cropWidth = right - left;
var cropHeight = bottom - top;
var cropX = top;
var cropY = left;
var cacheBitmap = new Bitmap(cropWidth, cropHeight, PixelFormat.Format32bppArgb);
using (var cacheGraphics = Graphics.FromImage(cacheBitmap)) {
cacheGraphics.DrawImage(context.Image, new Rectangle(0, 0, cropWidth, cropHeight), cropX, cropY, cropWidth, cropHeight, GraphicsUnit.Pixel);
}