C# - 裁剪透明/白色空间

时间:2010-07-17 11:51:51

标签: c# asp.net image-processing gdi+ crop

我正在尝试从图像中删除所有白色或透明像素,留下实际图像(裁剪)。我尝试了一些解决方案,但似乎都没有。有什么建议,还是我要花一夜的时间来编写图像裁剪代码?

5 个答案:

答案 0 :(得分: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);
  }

答案 1 :(得分:3)

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
}

请注意,此功能会因为污垢而变慢。 GetPixel()速度令人难以置信,并且在循环内访问Width的{​​{1}}和Height属性也很慢。 Bitmap是实现此目的的正确方法 - StackOverflow上有大量示例。

答案 2 :(得分:2)

在WPF中,我们有一个WriteableBitmap类。这是你在寻找什么?如果是这种情况,请查看http://blogs.msdn.com/b/jgalasyn/archive/2008/04/17/using-writeablebitmap-to-display-a-procedural-texture.aspx

答案 3 :(得分:2)

每像素检查应该可以解决问题。扫描每一行,从顶部找到空行&amp;在底部,扫描每一行以找到左边和正确的约束(这可以在一行中使用行或列完成)。找到约束时 - 将图像的一部分复制到另一个缓冲区。

答案 4 :(得分:0)

我找到了一种方法,可以在大约10分钟内批量修剪几千个.jpg文件,但我没有在代码中执行此操作。我使用了Snag-It Editor的Convert功能。我不知道这是否适合您,如果您需要进行一次修剪或者您的需求正在进行中,但是对于软件的价格而言,这并不是很多,我认为这是一个不错的解决方法。 (我不代表Techsmith工作或代表Techsmith。)

乔伊

相关问题