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
  1. public static Bitmap CropWhiteSpace(Bitmap bmp)
  2. {
  3. int w = bmp.Width;
  4. int h = bmp.Height;
  5. int white = 0xffffff;
  6. Func<int, bool=""> allWhiteRow = r =>
  7. {
  8. for (int i = 0; i < w; ++i)
  9. if ((bmp.GetPixel(i, r).ToArgb() & white) != white)
  10. return false;
  11. return true;
  12. };
  13. Func<int, bool=""> allWhiteColumn = c =>
  14. {
  15. for (int i = 0; i < h; ++i)
  16. if ((bmp.GetPixel(c, i).ToArgb() & white) != white)
  17. return false;
  18. return true;
  19. };
  20. int topmost = 0;
  21. for (int row = 0; row < h; ++row)
  22. {
  23. if (!allWhiteRow(row))
  24. break;
  25. topmost = row;
  26. }
  27. int bottommost = 0;
  28. for (int row = h - 1; row >= 0; --row)
  29. {
  30. if (!allWhiteRow(row))
  31. break;
  32. bottommost = row;
  33. }
  34. int leftmost = 0, rightmost = 0;
  35. for (int col = 0; col < w; ++col)
  36. {
  37. if (!allWhiteColumn(col))
  38. break;
  39. leftmost = col;
  40. }
  41. for (int col = w - 1; col >= 0; --col)
  42. {
  43. if (!allWhiteColumn(col))
  44. break;
  45. rightmost = col;
  46. }
  47. if (rightmost == 0) rightmost = w; // As reached left
  48. if (bottommost == 0) bottommost = h; // As reached top.
  49. int croppedWidth = rightmost - leftmost;
  50. int croppedHeight = bottommost - topmost;
  51. if (croppedWidth == 0) // No border on left or right
  52. {
  53. leftmost = 0;
  54. croppedWidth = w;
  55. }
  56. if (croppedHeight == 0) // No border on top or bottom
  57. {
  58. topmost = 0;
  59. croppedHeight = h;
  60. }
  61. try
  62. {
  63. var target = new Bitmap(croppedWidth, croppedHeight);
  64. using (Graphics g = Graphics.FromImage(target))
  65. {
  66. g.DrawImage(bmp,
  67. new RectangleF(0, 0, croppedWidth, croppedHeight),
  68. new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
  69. GraphicsUnit.Pixel);
  70. }
  71. return target;
  72. }
  73. catch (Exception ex)
  74. {
  75. throw new Exception(
  76. string.Format("Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight),
  77. ex);
  78. }
  79. }
  80. </int,></int,>
public static Bitmap CropWhiteSpace(Bitmap bmp)
{
  int w = bmp.Width;
  int h = bmp.Height;
  int white = 0xffffff;
 
  Func<int, bool=""> allWhiteRow = r =>
  {
    for (int i = 0; i < w; ++i)
      if ((bmp.GetPixel(i, r).ToArgb() & white) != white)
        return false;
    return true;
  };
 
  Func<int, bool=""> 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);
  }
}

</int,></int,>
To test code you can try this
  1. [Test]
  2. public void Test()
  3. {
  4. var inputPath = "image.png";
  5. var outputPath = inputPath.Replace(".png", "-out.png");
  6. var bitmap = new Bitmap(inputPath);
  7. var cropped = CropWhiteSpace(bitmap);
  8. cropped.Save(outputPath, ImageFormat.Png);
  9. }
[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
  1. using (Bitmap bitmap = new Bitmap(pngpath))
  2. {
  3. using (MemoryStream ms = new MemoryStream())
  4. {
  5. var cropped = CropWhiteSpace(bitmap);
  6. cropped.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  7. ms.WriteTo(context.Response.OutputStream);
  8. //cropped.Save(outputPath, System.Drawing.Imaging.ImageFormat.Png);
  9. //ms.WriteTo(context.Response.OutputStream);
  10. }
  11. }
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);
 }
}

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.