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
To test code you can try this
OR in ASP.net as
- 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,>
- [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);
- }
- 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);
- }
- }