-
Notifications
You must be signed in to change notification settings - Fork 29
Input Types & Output Functions
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"}
whereimage
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.
- 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:
- svg
Future: ico, exe, dll
To open up every page of a PDF document use:
; 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
To make the background of an image transparent such as when loading a sprite use:
ImagePutWindow({sprite: true, image: "character.bmp"})
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 commonly called pBitmap
.
Buffer - This can be a smart pointer created by ImagePutBuffer
. Or any object with a sufficient combination of .ptr
, .size
, .width
, .height
, .stride
, and .pitch
. See Reading an Image From Memory for details.
; Creates a 800 x 800 image from memory.
shape := {ptr: p, size: size, width: 800, height:800, stride: 800}
ImagePutWindow(shape)
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. If an hBitmap is not selected onto the device context, a default black 1x1 pixel will be returned.
Desktop - The literal case insensitive string "desktop"
refers to the first window anchored behind the desktop icons. This special window can be created by the result of ImagePutDesktop
or another third party program.
EncodedBuffer - Any image encoded as a file format such as WEBP stored inside a block of memory. This is different from a regular buffer object which stores pixel data directly. Imagine loading a PNG file into memory without decoding it.
File - A file path to an image. Supported image formats
ImagePutWindow("cats.jpg")
HBitmap - Handle to a GDI bitmap.
Note: 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. Similar to base64 encoding except takes up more space.
HIcon / HCursor - Handle to a GDI icon or cursor. The only difference is the presence of an (x, y) coordinate that determines the hotspot or a point on the image that preformes a clicking action.
Monitor - A monitor number between 0 and the number of monitors connected to the PC. The number 0
denotes the entire virtual screen. The number 1
denotes the primary monitor. The number 2
denotes a secondary number and so on...
ImagePutWindow(0) ; Whole screen
ImagePutWindow(1) ; First monitor
ImagePutWindow(2) ; Second monitor
Object - Any object with a .pBitmap
property.
RandomAccessStream - Pointer to an IRandomAccessStream interface.
SafeArray - A COM Object created with ComObjArray(0x11, size)
.
Screenshot - Screen coordinates in an [x,y,w,h]
or [x,y,w,h,r] array. When a [WinTitle](https://www.autohotkey.com/docs/misc/WinTitle.htm) is specified as
r, the
(x, y)` become relative to that window. Uses BitBlt.
Note: A special syntax exists to take a screenshot of a window by specifying
ImagePutWindow({screenshot: [WinTitle](https://www.autohotkey.com/docs/misc/WinTitle.htm))
Warning:
ahk_class
is case sensitive.
; 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"}) ; Could be ahk_class Notepad (case sensitive)
; Use object notation to add crop or scale:
ImagePutWindow({screenshot: "ahk_class notepad", crop: [0, 0, 100, 100]})
SharedBuffer - Should be created via ImagePutSharedBuffer
. A global Windows name that denotes a file mapping object that is shared between processes. If you wish to create your own FileMapping prefix your global name with ImagePut_
and omit the prefix when using ImagePut. The structure of an ImagePut specific FileMapping is the width and height as 32-bit unsigned integers followed by the image pixels. The stride or pitch can be interpreted from the size of the FileMapping and the height.
Stream - Pointer to an IStream interface. This can be a memory stream, a file stream, an IWICStream, or anything that inherits from IStream.
Uri - A base64 string that begins with meta such as data:image/png;base64,
.
Url - A url must begin with https://
or ftp://
.
Wallpaper - The literal case insensitive string "wallpaper"
.
WICBitmap - Pointer to a Windows Imaging Component bitmap commonly named IWICBitmap
.
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.
Warning:
ahk_class
is case sensitive.
; 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") ; Could be ahk_class Notepad (case sensitive)
; 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
The ImagePut.ImageType(image)
function can be used to return one of the above strings.
; The following returns the string: "Url"
MsgBox ImagePut.ImageType("https://picsum.photos/200")
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - 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 encoded as png.
base64 := ImagePutBase64("cats.jpg", "png")
; Compress jpeg further.
base64 := ImagePutBase64("cats.jpg", "jpg", 30)
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.FileToBitmap("cats.jpg") ; 4356 fps (built-in function)
Returns a buffer object with .ptr
, .size
, and .width
x .height
properties. 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
. See: PixelSearch & ImageSearch for additional options.
; 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 an 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!"
; Iterate over the image
pic := ImagePutBuffer([0, 0, 100, 100]) ; Capture 100 x 100 from top-left of screen
for x, y in pic
pic[x, y] := 0x00FF00 ; Turns every pixel green.
pic.show(1) ; Or ImagePutWindow(pic)
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. Preserves GIF and WEBP animations when possible. See the decode flag for details.
; Saves the file onto the clipboard.
ImagePutClipboard("cats.jpg")
; Copy animated GIFs too!
ImagePutClipboard("https://github.com/iseahound/ImagePut/assets/9779668/b8ff9e16-5662-4853-bb04-70428b60f122")
- 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)
- 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)
Returns "desktop"
. Creates an invisible window behind the desktop icons containing the image. See ImagePutWindow for details.
Warning! This functionality relies on an unsupported and undocumented feature.
; Show the image behind the desktop icons.
ImagePutDesktop("cats.jpg")
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.
Returns a buffer object that contains the encoded image. Similar to an IStream except stored inside an AutoHotkey Buffer object. This buffer object does not contain any additional methods or properties beyond ptr
and size
.
; Place the encoded WEBP inside a buffer.
buf := ImagePutEncodedBuffer("https://mathiasbynens.be/demo/animated-webp-supported.webp")
ImageShow(buf) ; Note that all frames are preserved because the image was not decoded.
- default - If no explorer window is found, specifies a default location to place the file such as
A_Desktop
. If omitted, no paste will be performed.
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.
; 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)
- filepath - Can be a filename
D:\Pictures\photo.png
or a folderD:\Pictures\
. ⬅️ Note the ending backslash for folders.- Creates all the folders in filepath.
- If there is no directory, default to the current working directory.
- If there is no filename, default to the current date and time.
- If there is no extension, default to the original encoding if available, else PNG.
- Supported extensions: bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif.
- For example, use
D:\Pictures\.gif
with no filename to save all images as GIFs. - If the last token matches an extension such as bmp in
C:\Photos\bmp
, the output directory will beC:\Photos\
and the file becomes<Timestamp>.gif
. - For convenience, if the filename is
0
or1
, images will be saved as an ascending sequence of natural numbers.- All other filenames except timestamps,
0
, and1
will overwrite existing files of the same name.
- All other filenames except timestamps,
- 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)
; Creates a file with a default name.
ImagePutFile("https://picsum.photos/1000") ; Filename: 2024-06-18 00꞉20꞉18.jpg
; Save image as a GIF.
ImagePutFile("https://picsum.photos/1000", ".gif") ; or "gif"
; Place image inside 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"
; Special Case: Use 0 or 1 as the filename to save the filename as 1.jpg, 2.jpg, 3.jpg... etc.
ImagePutFile("cats.jpg", 0) ; or "1.gif"
- 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")
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - 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")
Returns an hIcon handle.
; Create an hIcon.
hIcon := ImagePutHIcon("cats.jpg")
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - 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")
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - 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")
- 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")
- name - A Windows-level global name for the FileMapping object.
Returns a buffer object that can be opened in another process. See: PixelSearch and ImageSearch for additional methods and properties. This function allows one script to communicate with another script using interprocess communication. Changes made to the image in one script will affect the other script.
Script 1
#include ImagePut.ahk
a := ImagePutSharedBuffer("https://picsum.photos/800", "test123")
a.show(1, "Main Script") ; Don't close this window unless you make the script persistent.
MsgBox "change picture to blue?"
for x, y in a
a[x, y] := 0x0ABAB5
; Re-run the worker script to see changes!
Script 2
#include ImagePut.ahk
; Read the shared memory only.
ImagePutWindow("test123", "Worker Script Test #1")
; or if you need to open the buffer for two-way communication
b := ImagePutSharedBuffer("test123")
b.show(1, "Worker Script Test #2")
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - 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)
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - 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 except a MIME type is added such as: image/webp
. Can be used on all files, not just images.
; Creates a URI base64 string
URI := ImagePutURI("cats.jpg") ; data:image/jpeg;base64,/9j/4QDeRX
- extension - bmp, dib, rle, jpg, jpeg, jpe, jfif, gif, tif, tiff, png, heic, hif. Can be written as
gif
,.gif
or*.gif
. Defaults to PNG or the original extension when possible. - quality - For JPEG images, a value from 0-100 denoting the quality of the encoding.
Uploads the image to Imgur and returns a URL. Useful for testing purposes only. YOU WILL GET IP BANNED FOR ABUSE.
Note 1: Images are permanently uploaded. Do not use this function with sensitive data. NO DELETION IS POSSIBLE.
Note 2: I am not the owner of the API key.
; Upload image to Imgur
Run ImagePutUrl("cats.jpg")
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")
Returns a pointer to a WICBitmap interface.
; Create a WICBitmap.
wicBitmap := ImagePutWICBitmap("cats.jpg")
- 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.
- playback - If True, animations will be played when the window is shown. Defaults to True.
- cache - If True, all animation frames are cached into memory. If False, animations may lag as frames are decoded. Defaults to False.
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")
See ImagePutWindow for parameter descriptions. Same as ImagePutWindow except the image is shown without a titlebar caption.
ImageShow("cats.jpg")
width := ImageWidth("cats.jpg")
height := ImageHeight("cats.jpg")
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)
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?