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:
-
Create a
GdPictureImaging
object. -
Select the image by passing its path to the
CreateGdPictureImageFromFile
method of theGdPictureImaging
object. -
Check if the image has inverted colors by passing the image ID to the
IsNegative
method of theGdPictureImaging
object. -
If the source image has inverted colors, reverse the colors by passing the image ID to the
FxNegative
method of theGdPictureImaging
object. -
Save the output in a new image with the
SaveAsPNG
method of theGdPictureImaging
object. -
Release the image resource with the
ReleaseGdPictureImage
method of theGdPictureImaging
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