AutoContrast.vb
''
'' This code is part of GrapeCity Documents for Imaging samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
''
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports System.Linq
Imports System.Numerics
Imports GrapeCity.Documents.Drawing
Imports GrapeCity.Documents.Text
Imports GrapeCity.Documents.Imaging

'' This sample demonstrates how to use GrayscaleBitmap.AutoContrast()
'' to automatically adjust the contrast of a black and white image.
Public Class AutoContrast
    Function GenerateImage(
            Optional pixelWidth As Integer = 1024,
            Optional pixelHeight As Integer = 1024,
            Optional opaque As Boolean = True,
            Optional dpiX As Single = 96,
            Optional dpiY As Single = 96) As GcBitmap

        opaque = True
        Dim bmp = New GcBitmap(pixelWidth, pixelHeight, opaque, dpiX, dpiY)
        Using origBmp = New GcBitmap()
            '' Load a sample photo:
            Dim imagePath = Path.Combine("Resources", "ImagesBis", "tremblant.png")
            Dim grayBmp As GrayscaleBitmap
            Using stm = New FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.RandomAccess)
                origBmp.Load(stm)
                origBmp.Opaque = opaque
                grayBmp = origBmp.ToGrayscaleBitmap()
            End Using

            '' Resize the original photo to fit two versions on the resulting bitmap:
            Dim w = pixelWidth
            Dim h = pixelHeight / 2
            Using sizedBmp = origBmp.Resize(w, h, InterpolationMode.Cubic)
                '' Copy the resized original into the upper half of the resulting bitmap:
                bmp.BitBlt(sizedBmp, 0, 0)
                '' Auto adjust the contrast of the original image and copy the result into the lower half:
                grayBmp.AutoContrast()
                Using tbmp = grayBmp.ToGcBitmap()
                    bmp.BitBlt(tbmp, 0, h)
                End Using
            End Using

            '' Add captions (original and adjusted images):
            Dim lineh = 2
            Using g = bmp.CreateGraphics(Nothing)
                Dim foreColor = Color.Yellow
                Dim backColor = Color.Blue
                Dim fnt = Font.FromFile(Path.Combine("Resources", "Fonts", "cour.ttf"))
                g.DrawLine(0, h, w * 2, h, New Pen(Color.Gray, lineh * 2))
                Dim tf = New TextFormat() With {.Font = fnt, .FontSize = 18, .ForeColor = foreColor, .BackColor = backColor, .FontBold = True}
                Dim th = g.MeasureString("QWERTY", tf).Height
                g.DrawString(" Original image ", tf, New PointF(0, h - th + lineh))
                g.DrawString(" Auto contrast applied ", tf, New PointF(0, h * 2 + lineh - th + lineh))
            End Using
        End Using
        Return bmp
    End Function
End Class