Auto-Invert Images and PDFs in C#

Negative images and documents have reverse or inverted colors. For example, the text is white and the background is black. This can be an issue because intelligent document recognition assumes that images and documents have normal colors. This guide explains how to automatically detect if images and documents have inverted colors and how to reverse the colors.

To automatically detect inverted colors in an image and reverse them, follow these steps:

  1. Create a GdPictureImaging object.

  2. Select the image by passing its path to the CreateGdPictureImageFromFile method of the GdPictureImaging object.

  3. Check if the image has inverted colors by passing the image ID to the IsNegative method of the GdPictureImaging object.

  4. If the source image has inverted colors, reverse the colors by passing the image ID to the FxNegative method of the GdPictureImaging object.

  5. Save the output in a new image with the SaveAsPNG method of the GdPictureImaging object.

  6. Release the image resource with the ReleaseGdPictureImage method of the GdPictureImaging object.

The example below checks if the colors are inverted in an image file. If the colors are inverted, the example reverses the colors and saves the output in a new image file:

using GdPictureImaging gdpictureImaging = new GdPictureImaging();
// Load the image from a file.
int imageId = gdpictureImaging.CreateGdPictureImageFromFile(@"C:/temp/source.png");
// Check if the image has inverted colors.
bool isNegative = gdpictureImaging.IsNegative(imageId);
// Check if the image has inverted colors.
if (isNegative)
{
    // Reverse the colors.
    gdpictureImaging.FxNegative(imageId);
    gdpictureImaging.SaveAsPNG(imageId, @"C:/temp/output.png");
}
// Release the image resource.
gdpictureImaging.ReleaseGdPictureImage(imageId);
Using gdpictureImaging As GdPictureImaging = New GdPictureImaging()
    ' Load the image from a file.
    Dim imageId As Integer = gdpictureImaging.CreateGdPictureImageFromFile("C:/temp/source.png")
    ' Check if the image has inverted colors.
    Dim isNegative As Boolean = gdpictureImaging.IsNegative(imageId)
    ' Check if the image has inverted colors.
    If isNegative Then
        ' Reverse the colors.
        gdpictureImaging.FxNegative(imageId)
        gdpictureImaging.SaveAsPNG(imageId, "C:/temp/output.png")
    End If
    ' Release the image resource.
    gdpictureImaging.ReleaseGdPictureImage(imageId)
End Using
Used Methods

Related Topics