Image Object

class Image extends Object

Captures, loads, creates, draws, transforms, searches and saves images across platforms.

This class is exported by the KS module.

Table of Contents

Creating and Capturing Images

Image

Picture := Image(Source)

Creates an image from a file path, another Image or a native bitmap handle.

Create

Picture := Image.Create(Width, Height , Background, Scale)

Creates an ARGB canvas. If Background is omitted or blank, the canvas is fully transparent. Scale optionally sets the drawing scale.

FromBuffer

Picture := Image.FromBuffer(Data, Width, Height , BytesPerPixel := 4)

Creates an image from tightly packed pixel bytes. One byte per pixel represents 8-bit grayscale; four bytes represent RGBA. This is the inverse of GetPixelData.

FromFile

Picture := Image.FromFile(Path , Width, Height, IconNumber)

Loads an image from a file. Optional dimensions resize the loaded image; IconNumber selects an icon resource where applicable.

FromBitmap

Picture := Image.FromBitmap(Handle)

Copies an image from a native bitmap handle.

FromClipboard

Picture := Image.FromClipboard()

Copies the image currently held by the clipboard. Returns an empty string if the clipboard contains no image. This is the round-trip counterpart of CopyImageToClipboard.

FromDesktop

Picture := Image.FromDesktop()

Captures the whole virtual desktop.

FromMonitor

Picture := Image.FromMonitor(MonitorNumber)

Captures one monitor.

FromRect

Picture := Image.FromRect(X, Y, Width, Height)

Captures a screen rectangle in absolute screen coordinates. Pixel CoordMode does not affect these coordinates.

FromWindow

Picture := Image.FromWindow(WinTitle , Options, WinText, ExcludeTitle, ExcludeText)

Captures the whole matching window, including its title bar. Occluded windows are captured correctly except on compositors which expose only foreign-toplevel information.

Options can be a capture-mode number or an object. On Windows, modes 0 and 1 use GetDC with BitBlt, modes 2 and 3 use PrintWindow, and mode 4 (the default) uses PrintWindow with PW_RENDERFULLCONTENT for hardware-accelerated windows. Mode 5 (UWP capture) is not implemented.

{decorations: false} requests client-area-only capture on a platform which can honor it, such as KWin. Other platforms ignore this property.

Colors and Fonts

A color can be a name such as "Red", an opaque 0xRRGGBB value, or a 0xAARRGGBB value with alpha. To preserve a fully transparent 00 alpha, pass an eight-digit string or the color name "Transparent"; a numeric 0x00RRGGBB is indistinguishable from an opaque RGB value.

Fonts use the same two arguments as Gui.SetFont: an Options string of sSize plus optional bold, italic, underline, strike, norm, wWeight or qQuality tokens (such as "s16 bold italic"), and a separate FontName. An unrecognized option throws ValueError; pass the text color as DrawText's Color parameter, not a c option.

Drawing

Drawing methods are chainable and are applied lazily.

MethodEffect
Clear([Color])Clears the canvas, optionally to a color.
DrawLine(X1, Y1, X2, Y2 [, Color, Thickness])Draws a line.
DrawRect(X, Y, W, H [, Color, Thickness])Draws a rectangle outline.
FillRect(X, Y, W, H [, Color])Fills a rectangle.
DrawRoundRect(X, Y, W, H, Radius [, Color, Thickness])Draws a rounded-rectangle outline.
FillRoundRect(X, Y, W, H, Radius [, Color])Fills a rounded rectangle.
DrawEllipse(X, Y, W, H [, Color, Thickness])Draws an ellipse outline.
FillEllipse(X, Y, W, H [, Color])Fills an ellipse.
DrawText(Text, X, Y [, Color, Options, FontName])Draws text using the font convention above.
DrawImage(Picture [, X, Y, W, H])Draws another image, optionally at the supplied position and size.
MeasureText(Text [, Options, FontName])Returns a {w, h} object with the size the text would occupy when drawn.

Transforms

Transform methods queue a lazy operation and return the Image so calls can be chained.

MethodEffect
Scale(Factor [, FactorY])Scales proportionally, or independently by axis.
Resize(Width, Height)Resizes to absolute dimensions. Make either one dimension negative to preserve aspect ratio from the other.
Rotate(Angle [, Background])Rotates by degrees.
Flip([Horizontal])Flips the image.
Crop(X, Y, Width, Height)Crops to a rectangle.
Grayscale()Converts color to grayscale.
Alpha(Factor)Multiplies each pixel's alpha by a value from 0 to 1.
Brightness(Amount)Adjusts brightness by a value from -1 to 1.
Contrast(Amount)Adjusts contrast by a value from -1 to 1.

Output and Pixels

MethodEffect
Copy()Returns an independent copy.
Save(Filename)Applies pending operations and writes the image to a file.
ToBitmap()Applies pending operations and returns a native bitmap handle.
Show([Title, Wait])Shows a preview window. If Wait is non-zero, blocks until it closes.
GetPixel(X, Y)Returns the full 0xAARRGGBB pixel value.
SetPixel(X, Y, Color)Sets a pixel from an RGB or ARGB color.

GetPixelData

Data := Picture.GetPixelData(BytesPerPixel := 1)

Returns a tightly packed Buffer. Use 1 for grayscale or 4 for RGBA. The data is suitable for native calls and OCR libraries.

SetPixelData

Picture.SetPixelData(Data , BytesPerPixel := 4)

Overwrites the image from a tightly packed Buffer. Use 1 for grayscale or 4 for RGBA.

Searches compare RGB values and ignore alpha. Each method takes an optional region as flat X, Y, W, H parameters; each region parameter defaults independently, with an omitted origin meaning 0 and an omitted size running to the far edge, so Search(Needle, 100, 100) scans from (100, 100) to the bottom-right corner. Regions are clamped to the image and returned coordinates remain absolute image pixels.

Search

Match := Picture.Search(Needle , X, Y, Width, Height, Variation, Trans, Direction)

Finds one sub-image. On success, returns {x, y} for its top-left; on failure, returns an empty string, so if Match := Picture.Search(Needle) is the idiomatic use. Variation is the per-channel tolerance from 0 to 255. Trans specifies a needle color which matches any color. Direction uses the ImageSearch scan directions 1 through 9 to choose which match wins.

SearchAll

Matches := Picture.SearchAll(Needle , X, Y, Width, Height, Variation, Trans, Direction)

Returns every match as an Array of {x, y} objects, ordered by Direction. If none are found, the array is empty, so check Matches.Length.

SearchPixel

Match := Picture.SearchPixel(Color , X, Y, Width, Height, Variation, Direction)

Finds the first matching pixel. On success, returns {x, y, color}, where color is the actual full ARGB pixel value; on failure, returns an empty string. Direction selects the scan's starting corner: 1 is the top-left (the default), 2 the top-right, 3 the bottom-left and 4 the bottom-right. The image-search directions 5 through 9 do not apply to a pixel scan and throw ValueError.

Properties and Lifetime

PropertyDescription
OriginX, OriginYRead-only screen origin recorded by a capture factory.
ScaleX, ScaleYRead-only HiDPI pixel scale used to map image positions back to screen coordinates.

Rotate and Flip invalidate the screen-origin mapping, and Rotate also invalidates the scale mapping: the affected properties then read an empty string instead of a stale value.

SetOrigin

Picture.SetOrigin(X, Y , ScaleX, ScaleY)

Re-anchors the screen mapping: sets the origin and, optionally, the pixel scale (ScaleY defaults to ScaleX). Use it to give a FromBuffer or file image a screen position, or to restore the mapping after Rotate or Flip invalidated it.

Using an Image after it has been disposed throws an exception.

Examples

#Import "Ks" { Image }

Image.FromRect(100, 100, 640, 480)
    .Grayscale()
    .Resize(320, -1)
    .Save("capture.png")

Overlay, ImageSearch, PixelSearch, Clipboard Helper Functions, Platform Support