C# Crop white space from around the image

This code will crop the image based on all white and transparent pixels from around the image
public static Bitmap CropWhiteSpace(Bitmap bmp)
{
  int w = bmp.Width;
  int h = bmp.Height;
  int white = 0xffffff;
 
  Func allWhiteRow = r =>
  {
    for (int i = 0; i < w; ++i)
      if ((bmp.GetPixel(i, r).ToArgb() & white) != white)
        return false;
    return true;
  };
 
  Func allWhiteColumn = c =>
  {
    for (int i = 0; i < h; ++i)
      if ((bmp.GetPixel(c, i).ToArgb() & white) != white)
        return false;
    return true;
  };
 
  int topmost = 0;
  for (int row = 0; row < h; ++row)
  {
    if (!allWhiteRow(row))
      break;
    topmost = row;
  }
 
  int bottommost = 0;
  for (int row = h - 1; row >= 0; --row)
  {
    if (!allWhiteRow(row))
      break;
    bottommost = row;
  }
 
  int leftmost = 0, rightmost = 0;
  for (int col = 0; col < w; ++col)
  {
    if (!allWhiteColumn(col))
      break;
    leftmost = col;
  }
 
  for (int col = w - 1; col >= 0; --col)
  {
    if (!allWhiteColumn(col))
      break;
    rightmost = col;
  }
 
  if (rightmost == 0) rightmost = w; // As reached left
  if (bottommost == 0) bottommost = h; // As reached top.
 
  int croppedWidth = rightmost - leftmost;
  int croppedHeight = bottommost - topmost;
 
  if (croppedWidth == 0) // No border on left or right
  {
    leftmost = 0;
    croppedWidth = w;
  }
 
  if (croppedHeight == 0) // No border on top or bottom
  {
    topmost = 0;
    croppedHeight = h;
  }
 
  try
  {
    var target = new Bitmap(croppedWidth, croppedHeight);
    using (Graphics g = Graphics.FromImage(target))
    {
      g.DrawImage(bmp,
        new RectangleF(0, 0, croppedWidth, croppedHeight),
        new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
        GraphicsUnit.Pixel);
    }
    return target;
  }
  catch (Exception ex)
  {
    throw new Exception(
      string.Format("Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight),
      ex);
  }
}

To test code you can try this
[Test]
public void Test()
{
  var inputPath = "image.png";
  var outputPath = inputPath.Replace(".png", "-out.png");
 
  var bitmap = new Bitmap(inputPath);
  var cropped = CropWhiteSpace(bitmap);
  cropped.Save(outputPath, ImageFormat.Png); 
}
OR in ASP.net as
using (Bitmap bitmap = new Bitmap(pngpath))
{
 using (MemoryStream ms = new MemoryStream())
 {
  var cropped = CropWhiteSpace(bitmap);
  cropped.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  ms.WriteTo(context.Response.OutputStream);
  //cropped.Save(outputPath, System.Drawing.Imaging.ImageFormat.Png); 

  //ms.WriteTo(context.Response.OutputStream);
 }
}

Comments

  1. hello ,
    I try using this function however in VS studio 2010 with .net 4.0 I'm getting
    a error the the 'System.Func' requires 1 type arguments" I'm not sure what I might have to change to get it to work.

    ReplyDelete
  2. I'm not sure why but this weblog is loading extremely slow for me. Is anyone else having this issue or is it a issue on my end? I'll check back later and see if the problem still exists.

    ReplyDelete
  3. I'm extremely inspired together with your writing abilities as well as with the layout on your blog. Is this a paid subject or did you modify it yourself? Anyway stay up the excellent quality writing, it's rare to peer a great weblog like this one nowadays..

    ReplyDelete
  4. Lucky Niki - Casino in Japan
    Lucky Niki is a Japanese online casino. 카지노사이트 The site is operated by GAMES Entertainment Limited in ラッキーニッキー Tokyo. It is a Japanese-focused online gambling william hill site

    ReplyDelete

Post a Comment

Popular posts from this blog

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=xx.0.0.0, Culture=neutral, PublicKeyToken='xxx' or one of its dependencies.

The specified version string contains wildcards, which are not compatible with determinism.