在c#中从图像右侧裁剪留白
本文关键字:裁剪 留白 图像 | 更新日期: 2023-09-27 18:08:21
我有一些图片,它们在底部和右侧包含了很多空白。我想在显示给用户之前剪掉空白
到目前为止,我已经实现了从底部检测非白色像素。像素格式为Format32BppArgb。
byte[] byteImage = Convert.FromBase64String(imageString);
MemoryStream ms = new MemoryStream(byteImage, 0, byteImage.Length);
ms.Write(byteImage, 0, byteImage.Length);
Image image = Image.FromStream(ms, true);
Bitmap bmpImage = new Bitmap(image);
int imageDataHeight = bmpImage.Height;
int imageWidth = bmpImage.Width;
int imageHeight = bmpImage.Height;
BitmapData data = bmpImage.LockBits(new Rectangle(0, 0, imageWidth, imageHeight), ImageLockMode.ReadOnly, bmpImage.PixelFormat);
try
{
unsafe
{
int width = data.Width / 2;
for (int y = data.Height-1; y > 0 ; y--)
{
byte* row = (byte*)data.Scan0 + (y * data.Stride);
int blue = row[width * 3];
int green = row[width * 2];
int red = row[width * 1];
if ((blue != 255) || (green != 255) || (red != 255))
{
imageDataHeight = y + 50;
break;
}
}
}
}
finally
{
bmpImage.UnlockBits(data);
}
// cropping a rectangle based on imageDataHeight
// ...
如何正确地迭代从右到左开始的列并检测非白色像素?
这将给你的目标宽度:
unsafe int CropRight(BitmapData data)
{
int targetWidth = data.Width;
for (int x = data.Width - 1; x >= 0; x--)
{
bool isWhiteStripe = true;
for (int y = data.Height - 1; y > 0; y--)
{
if (!IsWhite(data, x, y))
{
isWhiteStripe = false;
break;
}
}
if (!isWhiteStripe)
break;
targetWidth = x;
}
return targetWidth;
}
int bytesPerPixel = 4; //32BppArgb = 4bytes oer pixel
int redOffset = 1; // 32BppArgb -> red color is the byte at index 1, alpha is at index 0
unsafe bool IsWhite(BitmapData data, int x, int y)
{
byte* row = (byte*)data.Scan0 + (y * data.Stride) + (x * bytesPerPixel);
int blue = row[redOffset + 2];
int green = row[redOffset + 1];
int red = row[redOffset];
// is not white?
if ((blue != 255) || (green != 255) || (red != 255))
{
return false;
}
return true;
}
然后,你可以裁剪图像:如何使用c#裁剪图像?