Input Types & Output Functions - iseahound/ImagePut GitHub Wiki

Usage

The following examples use "cats.jpg". Rename one of your own JPEGs or download one with ImagePut.

#Include *i ImagePut.ahk
#Include *i ImagePut (for v1).ahk
ImagePutFile({url: "https://picsum.photos/500"}, "cats.jpg")         ; Download "cats.jpg"

Examples

ImagePutWindow("cats.jpg")                                           ; Simple call
ImagePutWindow("cats.jpg", "This is a cute cat!")                    ; Title: This is a cute cat!
ImagePutWindow("cats.jpg", "This is a cute cat!", [0, 0])            ; Pos: Top left corner of screen

ImagePutWindow({file: "cats.jpg"})                                   ; Explicit input type "file"
ImagePutWindow({file: "cats.jpg", scale: 2})                         ; Scale 2x
ImagePutWindow({file: "cats.jpg", scale: 2, crop: [0, 0, 300, 300]}) ; Crop to 300 x 300

ImagePutWindow({file: "cats.jpg", scale: 2}, "This is a cute cat!")  ; Keyword + Positional Parameters
ImagePutWindow({file: "cats.jpg", scale: 2, crop: [0, 0, 300, 300]}, "This is a cute cat!", [0, 0])

If the input type is not known use image as the type.

ImagePutWindow({image: "cats.jpg", scale: 2}, "🐈🐈‍⬛🐈")            ; Unknown input type + keyword parameters

The description of ImagePutWindow(image, title, pos, style, styleEx, parent) contains:

  • image - Either a input such as "cats.jpg" or a wrapper object like {file: "cats.jpg"} which specifies the input type to be a file or {image: "cats.jpg"} where image is a generic type.
  • title - a custom title shown on the caption bar
  • pos - a rectangle array [x, y, w, h]
  • style - window style (rarely used)
  • styleEx - extended window style (rarely used)
  • parent - handle to the parent window (Your AutoHotkey script's main window by default)

Sometimes you do want to specify the input type, such as when the input may be ambiguous:

; Pretend I have an image viewer open with the title "cats.jpg"
ImagePutWindow({window: "cats.jpg"}, "❤️") ; In this case that window takes precedence over any files.

Supported Formats

  • bmp, dib, rle
  • jpg, jpeg, jpe, jfif
  • gif (supports animations)
  • emf (read only)
  • wmf (read only)
  • tif, tiff
  • png
  • ico (read only)
  • heic, hif
  • webp (supports animations, read only)
  • avif, avifs (read only)

The following formats are rendered:

  • pdf
  • svg

Future: ico, exe, dll

Input Types

base64 - A base64 string with an optional data URI scheme. Can start with data:image/png;base64,

; Transparent green pixel.
ImagePutWindow("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")

bitmap - Pointer to a GDI+ bitmap.

buffer - Any object with a .pBitmap property. This can be a smart pointer created by ImagePutBuffer.

clipboard - The built-in ClipboardAll variable.

Note: In AutoHotkey v1, ClipboardAll is equal to the empty string when used as a function parameter.

ImagePutWindow(ClipboardAll) ; AutoHotkey v1
ImagePutWindow(ClipboardAll) ; or ClipboardAll() for AutoHotkey v2

cursor - The built-in variable A_Cursor or any of its values.

dc - Handle to a device context. An hBitmap should be selected onto the device context.

desktop - The case insensitive string "desktop".

file - A file path to an image. Supported image formats: bmp, gif, jpg, png, tiff.

ImagePutWindow("cats.jpg")

hBitmap - Handle to a GDI bitmap. When converting a hBitmap with transparency, visually similar but not pixel perfect images are created due to the impreciseness of division. This is a result of converting from a pre-multiplied ARGB to an ARGB pixel format.

hex - A hexadecimal string representing an encoded image.

hIcon - Handle to a GDI icon.

monitor - The monitor number. The number 0 denotes the entire virtual screen.

ImagePutWindow(0) ; Whole screen
ImagePutWindow(1) ; First monitor
ImagePutWindow(2) ; Second monitor

pdf - A file path to a pdf file.

; Process a PDF document.
ImagePutWindow("document.pdf")

; Using a page number.
ImagePutWindow({pdf:"document.pdf", index:2}) ; page 2.

; Process every page.
loop
    try ImagePutWindow({pdf:"document.pdf", index:A_Index})
    catch
        break

RandomAccessStream - Pointer to a RandomAccessStream interface.

screenshot - Screen coordinates in an [x,y,w,h] or `[x,y,w,h,r] array where r is relative to a window. Can also be a hwnd or the window title. Uses BitBlt.

; From the top-left (0, 0) with 200 width and 200 height.
ImagePutWindow([0, 0, 200, 200])

; A 200 by 200 square relative to the current active window.
ImagePutWindow([0, 0, 200, 200, "A"])

; When using a hwnd or a Window Title, declare the image type as a screenshot. 
ImagePutWindow({screenshot: "ahk_class notepad"})

; Use object notation to add crop or scale:
ImagePutWindow({screenshot: "ahk_class notepad", crop: [0, 0, 100, 100]})

stream - Pointer to a stream interface. This can be a memory stream, a file stream, an IWICStream, or anything that inherits from IStream.

sprite - Must be explicitly declared as: {sprite:"character.bmp"}. Can be a file path or a url. Samples the top-left pixel and sets all pixels of that color as transparent.

ImagePutWindow({sprite: "character.bmp"})

url - A url must begin with https:// or ftp://.

wallpaper - The case insensitive string "wallpaper".

wicBitmap - Pointer to a Windows Imaging Component bitmap.

window - Any string that matches the window title. Is affected by SetTitleMatchMode. Use the special variable "A" to match the current active window. Supports ahk_id, ahk_class, ahk_pid, etc. See WinTitle for details. Uses the PrintWindow API.

; Window Title
ImagePutWindow("Untitled - Notepad")

; Window Handle
ImagePutWindow(0x1234)
ImagePutWindow("ahk_id" 0x1234) ; Recommended for safe checking of valid hwnd.

; Window Class
ImagePutWindow("ahk_class notepad")

; Current Active Window
ImagePutWindow("A")

; If you are having issues with window capture use a screenshot instead.
ImagePutWindow(["Untitled - Notepad"]) ; Similar to ImagePutWindow([x, y, w, h])

; Or declare the type as a screenshot:
ImagePutWindow({screenshot: "Untitled - Notepad", crop: [0, 0, 100, 100]}) ; Uses BitBlt for screen capture
ImagePutWindow({window: "Untitled - Notepad", crop: [0, 0, 100, 100]})     ; Uses PrintWindow for window capture

Output Functions

ImagePutBase64(image, extension, quality)

  • extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png. Can be written as .gif or *.gif. Keeps the original extension if possible. Defaults to PNG.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns a base64 string.

; Create a base64 string.
base64 := ImagePutBase64("cats.jpg")

; Base64 png encode.
base64 := ImagePutBase64("cats.jpg", "png")

; Compress jpeg further.
base64 := ImagePutBase64("cats.jpg", "jpg", 30)

ImagePutBitmap(image)

Returns a GDI+ bitmap pointer. Must call ImageDestroy() when finished to prevent a GDI+ object leak. Consider using ImagePutBuffer() instead.

; pToken := Gdip_Startup()            ; Alternative if #include Gdip_All.ahk
ImagePut.gdiplusStartup()             ; Initialize GDI+
pBitmap := ImagePutBitmap("cats.jpg") ; Create a pBitmap
ImagePutWindow(pBitmap)               ; Show the image
ImageDestroy(pBitmap)                 ; Dispose the bitmap

Note: The fastest way to reduce overhead is by calling the internal ImagePut.from_XXX function.

pBitmap := ImagePutBitmap("cats.jpg")        ; 1500 fps (same speed as ImagePutBuffer)
pBitmap := ImagePutBitmap({file:"cats.jpg"}) ; 2600 fps (skip type inference)
pBitmap := ImagePut.from_file("cats.jpg")    ; 4356 fps (built-in function)

ImagePutBuffer(image)

Returns a buffer object. This is a smart pointer that will automatically dispose of the bitmap when the variable is freed. It also contains its own GDI+ scope, so any calls to pToken := Gdip_Startup() or ImagePut.gdiplusStartup() are unnecessary. Access the raw pointer via buffer.pBitmap.

; Create a buffer object.
buf := ImagePutBuffer("cats.jpg")

; Get the pBitmap pointer.
ImagePutWindow(buf.pBitmap)

; Get bitmap width and height.
width := buf.width, height := buf.height

; Show color of pixel at x, y.
MsgBox % buf[20, 33] ; Returns a ARGB value.

; Find a white pixel using pixel search.
if xy := buf.PixelSearch(0xFFFFFF)
    MsgBox % xy[1] ", " xy[2]
else
    MsgBox % "Try again. No white pixel was found!"

ImagePutClipboard(image)

Returns an empty string in AutoHotkey v1, and the ClipboardAll() object in AutoHotkey v2. The image is placed onto the clipboard twice, once as a PNG stream supporting transparency and another as a bottom-up hBitmap.

; Saves the file onto the clipboard.
ImagePutClipboard("cats.jpg")

ImagePutCursor(image, xHotspot, yHotspot)

  • xHotspot, yHotspot - Specify the cursor’s “click point” using x and y coordinates. The default value is the center of the image.

Returns "A_Cursor". The image is set as the new cursor.

Warning! Setting your cursor to a large image may cover the entire screen.

; Sets an image as the cursor.
ImagePutCursor("cats.jpg", 0, 0) ; Set hotspot to be top-left.
Sleep 20000
ImageDestroy(A_Cursor) ; Same as: DllCall("SystemParametersInfo", "uint", 20, "uint", 0, "ptr", 0, "uint", 2)

ImagePutDC(image, alpha)

  • alpha - An RGB color can be specified as the replacement color for transparent pixels.

Returns a GDI device context handle.

; Create a device context with a pre-selected image.
hdc := ImagePutDC("cats.jpg")

; Replace any alpha transparency with a white background.
hdc := ImagePutDC("cats.jpg", 0xFFFFFF)

ImagePutDesktop(image)

Returns "desktop". Creates an invisible window behind the desktop icons containing the image.

Warning! This functionality relies on an unsupported and undocumented feature.

; Show the image behind the desktop icons.
ImagePutDesktop("cats.jpg")

ImagePutExplorer(image, default)

  • default - A_Desktop if not specified.

Returns the filepath of the image. Saves the image into the most recent explorer window the user has open. If this cannot be found, defaults to the default parameter or the desktop. If the mouse cursor is hovering the desktop, the file will be saved onto the desktop.

; This function is useful for copying images from Figma.
; Paste the image on the clipboard into an open explorer window.
ImagePutExplorer(ClipboardAll)

; Place the image into the user's documents folder if there are no explorer windows open.
ImagePutExplorer(ClipboardAll, A_MyDocuments)

ImagePutFile(image, filepath, quality)

  • filepath - The output filepath. Can be a filename or a folder.
    • If the directory is omitted, default to the current working directory.
    • If the filename is omitted, default to the current time.
    • If the extension is omitted, default to the original encoding if available, else PNG.
    • Use an ending backslash such as D:\Pictures\ to disambiguate directories from files.
    • Creates all folders in filepath.
    • An output directory can be used in combination with a file extension such as D:\Pictures\.gif to save all images as GIFs.
    • A filename that matches an extension such as D:\Pictures\gif is assumed to be the extension and the output filepath will be D:\Pictures\<Timestamp>.gif.
    • If the filename is 0 or 1, images will be saved as an ascending sequence of natural numbers.
      • All other filenames except timestamps, 0, and 1 will overwrite existing files of the same name.
    • Linux style forward slashes are supported.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns the filepath.

; Save the current mouse cursor 5x its original size. 
filepath := ImagePutFile({cursor: A_Cursor, scale: 5}, "cursor.png")
ImageShow(filepath)

; Create a file using the current timestamp.
ImagePutFile("cats.jpg")

; Create a file as a GIF.
ImagePutFile("cats.jpg", ".gif") ; or "gif"

; Create a file inside a directory.
ImagePutFile("cats.jpg", "pics\") ; Ending backslash is required to create new directories.

; Create a file inside a directory as a GIF.
ImagePutFile("cats.jpg", "pics\.gif") ; or "pics\gif"

; Create a file using an ascending sequence of numbers starting from 0 or 1.
ImagePutFile("cats.jpg", 0) ; or "1.gif"

ImagePutHBitmap(image, alpha)

  • alpha - An alpha color can be specified as the replacement color for transparent pixels.

Returns an hBitmap handle.

The pixel format of an hBitmap is pre-multiplied alpha RGB (pARGB). Therefore any conversion between pre-multiplied ARGB and ARGB will introduce rounding errors. The result is that any image with transparency will look visually identical to the source, but not be pixel perfect causing ImageEqual to fail. RGB images without an alpha channel are unaffected.

; Create an HBitmap.
hBitmap := ImagePutHBitmap("cats.jpg")

; Replace any alpha transparency with a white background.
hBitmap := ImagePutHBitmap("cats.jpg", 0xFFFFFF)

; The following test will fail because the image has alpha transparency.
hBitmap := ImagePutHBitmap("https://i.imgur.com/PBy1WBT.png")
MsgBox % ImageEqual(hBitmap, "https://i.imgur.com/PBy1WBT.png")

ImagePutHex(image, extension, quality)

  • extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png. Can be written as .gif or *.gif. Keeps the original extension if possible. Defaults to PNG.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns a hexadecimal string.

; Create a hexadecimal string.
hex := ImagePutHex("cats.jpg")

ImagePutHIcon(image)

Returns an hIcon handle.

; Create an hIcon.
hIcon := ImagePutHIcon("cats.jpg")

ImagePutRandomAccessStream(image, extension, quality)

  • extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png. Can be written as .gif or *.gif. Keeps the original extension if possible. Defaults to TIFF for speed.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns an interface pointer to a RandomAccessStream.

; Create an IRandomAccessStream.
pRandomAccessStream := ImagePutRandomAccessStream("cats.jpg")

ImagePutSafeArray(image, extension, quality)

  • extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png. Can be written as .gif or *.gif. Keeps the original extension if possible. Defaults to PNG.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns a SafeArray COM object. Useful for sending data to web APIs.

; Create a SafeArray.
SafeArray := ImagePutSafeArray("cats.jpg")

ImagePutScreenshot(image, alpha)

  • alpha - An alpha color can be specified as the replacement color for transparent pixels.

Returns an [x,y,w,h] array. Copies the image directly onto the screen’s device context. For temporary usage only, as the image can be drawn over by other applications.

; Temporarily show the image on the screen.
ImagePutScreenshot("cats.jpg")

ImagePutStream(image, extension, quality)

  • extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png. Can be written as .gif or *.gif. Keeps the original extension if possible. Defaults to TIFF for speed.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns an interface pointer to a stream. Do not call GlobalFree, ObjRelease will free the underlying memory when the reference count reaches zero.

; Create an IStream.
pStream := ImagePutStream("cats.jpg")

; Get the backing hGlobal from the stream.
DllCall("ole32\GetHGlobalFromStream", "ptr",pStream, "uint*",hData)

; Get a pointer and size to the encoded image.
pData := DllCall("GlobalLock", "ptr",hData, "ptr")
nSize := DllCall("GlobalSize", "uint",pData) 

ImagePutURI(image, extension, quality)

  • extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png. Can be written as .gif or *.gif. Keeps the original extension if possible. Defaults to PNG.
  • quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.

Returns a base64 string with a URI header. Same as ImagePutBase64. Can be used on all files, not just images.

; Create a URI base64 string.
URI := ImagePutURI("cats.jpg")

ImagePutWallpaper(image)

Returns "wallpaper". Sets the image as the wallpaper. Your desktop personalization settings determines if the image will be stretched, filled, fitted, centered, tiled or spanned.

; Set a temporary wallpaper.
ImagePutWallpaper("cats.jpg")

ImagePutWICBitmap(image)

Returns a pointer to a WICBitmap interface.

; Create a WICBitmap.
wicBitmap := ImagePutWICBitmap("cats.jpg")

ImagePutWindow(image, title, pos, style, styleEx, parent)

  • title - A string to be shown on the titlebar.
  • pos - An [x,y,w,h] coordinate array with optional elements describes the initial window position.
  • style - A hexadecimal value describing the window style.
  • styleEx - A hexadecimal value describing the extended window style.
  • parent - The hwnd of the parent window. Defaults to A_ScriptHwnd.

Returns a window handle. Displays the image in a window on a transparent background with a titlebar surrounded by a thin border. Move the window by dragging the image. Right click the window to close. Scales to fit the primary screen.

; Show the image.
ImagePutWindow("cats.jpg")

Additional Functions

ImageShow(image, title, pos, style, styleEx, parent)

Same functionality as ImagePutWindow except the image is shown without a titlebar and border.

ImageShow("cats.jpg")

ImageWidth(image), ImageHeight(image)

width := ImageWidth("cats.jpg")
height := ImageHeight("cats.jpg")

ImageDestroy(image)

This function can be used with the return value of any of the above functions to clean up any effects.

; Deletes the file.
filepath:= ImagePutFile("cats.jpg", "png")
ImageDestroy(filepath) ; Calls FileDelete

; Cleanup an hBitmap.
hBitmap := ImagePutHBitmap("cats.jpg")
ImageDestroy(hBitmap) ; Calls DeleteObject

; Release a stream.
pStream := ImagePutStream("cats.jpg")
ImageDestroy(pStream) ; Calls ObjRelease

; Restores the cursor.
cursor := ImagePutCursor("cats.jpg")
ImageDestroy(cursor)  ; Same as: DllCall("SystemParametersInfo", "uint", 20, "uint", 0, "ptr", 0, "uint", 2)

ImageEqual(images*)

Compares the pixel data of multiple images. Calling ImageEqual with one parameter will validate the image. Returns True if all images have the same pixel values, or False upon reaching the first different image.

; Ensure that cats.jpg contains valid pixel data.
ImageEqual("cats.jpg")

; Compares the cursor to a file.
ImageEqual(A_Cursor, "cats.jpg")

; Compares three things.
ImageEqual(A_Cursor, "cats.jpg", [0,0,100,100])

Warning! When using ImageEqual to validate pointers, it is up to the user to ensure that they are valid! A critical error will be thrown for integer values outside of the range 0-4095 and 0-65535 for AutoHotkey v1 and v2 respectively. Using ImageEqual to check for valid monitor numbers is therefore safe.

Note: Calling ImageEqual on an transparent hBitmap may return False. This is because comparing pre-multiplied alpha values introduces floating point precision errors. Consider 136/255 * 138 = 73.6. Now round 73.6 to 74. From the equation 136/255 * x = 74 find x. The value of x becomes 138.75, and is rounded to 139. Is the original value of 138 equal to 139?

⚠️ **GitHub.com Fallback** ⚠️