Ech*_*lon 5 c# asp.net gdi+ crop image-processing
我正在尝试从图像中删除所有白色或透明像素,留下实际图像(裁剪).我尝试了一些解决方案,但似乎都没有.有什么建议或者我打算过夜写图像裁剪代码?
Chr*_*lor 10
所以,你想要做的是找到顶部,最左边的非白色/透明像素和底部,最右边的非白色/透明像素.这两个坐标将为您提供一个矩形,然后您可以提取该矩形.
// Load the bitmap
Bitmap originalBitmap = Bitmap.FromFile("d:\\temp\\test.bmp") as Bitmap;
// Find the min/max non-white/transparent pixels
Point min = new Point(int.MaxValue, int.MaxValue);
Point max = new Point(int.MinValue, int.MinValue);
for (int x = 0; x < originalBitmap.Width; ++x)
{
for (int y = 0; y < originalBitmap.Height; ++y)
{
Color pixelColor = originalBitmap.GetPixel(x, y);
if (!(pixelColor.R == 255 && pixelColor.G == 255 && pixelColor.B == 255)
|| pixelColor.A < 255)
{
if (x < min.X) min.X = x;
if (y < min.Y) min.Y = y;
if (x > max.X) max.X = x;
if (y > max.Y) max.Y = y;
}
}
}
// Create a new bitmap from the crop rectangle
Rectangle cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
Bitmap newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height);
using (Graphics g = Graphics.FromImage(newBitmap))
{
g.DrawImage(originalBitmap, 0, 0, cropRectangle, GraphicsUnit.Pixel);
}
Run Code Online (Sandbox Code Playgroud)
public Bitmap CropBitmap(Bitmap original)
{
// determine new left
int newLeft = -1;
for (int x = 0; x < original.Width; x++)
{
for (int y = 0; y < original.Height; y++)
{
Color color = original.GetPixel(x, y);
if ((color.R != 255) || (color.G != 255) || (color.B != 255) ||
(color.A != 0))
{
// this pixel is either not white or not fully transparent
newLeft = x;
break;
}
}
if (newLeft != -1)
{
break;
}
// repeat logic for new right, top and bottom
}
Bitmap ret = new Bitmap(newRight - newLeft, newTop - newBottom);
using (Graphics g = Graphics.FromImage(ret)
{
// copy from the original onto the new, using the new coordinates as
// source coordinates for the original
g.DrawImage(...);
}
return ret
}
Run Code Online (Sandbox Code Playgroud)
请注意,此函数将非常慢。 GetPixel()
速度慢得令人难以置信,并且访问循环内的Width
和属性也很慢。 将是执行此操作的正确方法 - StackOverflow 上有大量示例。Height
Bitmap
LockBits
归档时间: |
|
查看次数: |
7490 次 |
最近记录: |