C# cropping bitmaps depending on bitmap location

140 Views Asked by At

I have a PDF file containing numerous pages of hand-written surveys. My C# application currently breaks each PDF page down into single Bitmap objects (each PDF page is a Bitmap object) and then uses various APIs to read the hand-written data from each Bitmap object and then enters the extracted data into a database.

My problem is, in order for my API extraction to work, each checkbox and each answer box needs to be in the exact same XY pixel location in every Bitmap. Because these PDF files are scanned images, each PDF page may be a few pixels off in any direction e.g. some PDF pages are a few pixels off to the left, right, top or bottom

Does anybody know if it is possible to crop a Bitmap based on some constant in each Bitmap? For example (please see Bitmap image below), if I could crop each Bitmap starting at the "S" in Secondary School Study at the top left of each page, then each Bitmap would be cropped at the exact same location and this would solve my problem of each checkbox and answer box being in the same XY locations.

Any advice would be appreciated

EDIT: the only possible solution I can think of is looping over each pixel, starting at the top left hand corner until it hits a black pixel (which would be the first "S" in Secondary School Study). Could I then crop the Bitmap from this location?

enter image description here

1

There are 1 best solutions below

0
On

I came up with a solution which was similar to the one I mentioned above. I scan over each pixel and until it reaches the first pixel in the "S" in Secondary School Study. I use this pixel X Y location to then crop a rectangle of a fixed height and width, starting at that location. I used bm.GetPixel().GetBrightness() to find out when the pixel reached the "S".

            Bitmap bm = new Bitmap(@"C:\IronPDFDoc\2.png", true);

            bool cropFlag = false;
            int cropX = 0;
            int cropY = 0;

            for (int y = 0; y < 155; y++)
            {
                for (int x = 0; x < 115; x++)
                {
                    float pixelBrightness = bm.GetPixel(x, y).GetBrightness();
                    if (pixelBrightness < 0.8 && cropFlag == false)
                    {
                        cropFlag = true;
                        cropX = x;
                        cropY = y;
                    }
                }
            }

            Rectangle crop = new Rectangle(cropX, cropY, 648, 915);
            Bitmap croppedSurvey = new Bitmap(crop.Width, crop.Height);

            using (Graphics g = Graphics.FromImage(croppedSurvey))
            {
                g.DrawImage(bm, new Rectangle(0, 0, croppedSurvey.Width, croppedSurvey.Height),
                                 crop,
                                 GraphicsUnit.Pixel);
            }

            croppedSurvey.Save(@"C:\IronPDFDoc\croppedSurvey.png", ImageFormat.Png);