photo(3tk)
photo(3tk) π Tk Built-In Commands
NAME β¨
photo β Full-color images, periodt! π¨β¨
SYNOPSIS π
image create photo ?name? ?options?
imageName blank
imageName cget option
imageName configure ?option? ?value option value ...?
imageName copy sourceImage ?option value(s) ...?
imageName data ?option value(s) ...?
imageName get x y ?option?
imageName put data ?option value(s) ...?
imageName read filename ?option value(s) ...?
imageName redither
imageName transparency subcommand ?arg ...?
imageName write filename ?option value(s) ...?
DESCRIPTION π¦
Okay bestie, so a photo is literally an image where every pixel can be any color AND have its own level of transparency β that's the alpha channel, no cap. π
A photo image is stored internally in full color (32 bits per pixel, highkey fancy), and it gets displayed using dithering if that's what it takes. You can get image data for a photo from a file or a string, or you can supply it from C code through a procedural interface. At the moment, only PNG, GIF, PPM/PGM, and (read- 2 only) SVG formats are supported, but there's an interface that lets you add more image file formats easily. A photo image is (semi)transparent if the image data it came from had transparency info. In regions where no image data has been supplied, it's fully transparent. You can also change transparency with the transparency set subcommand. β¨
CREATING PHOTOS π
Like all images, photos are created using the image create command. Photos support these options:
-data stringβ This sets the contents of the image as a string. The string 2 should contain data in the default list-of-lists form, binary data, or β for some formats β base64-encoded data (this is currently guaranteed to work for PNG and GIF images). The format of the string has to be one that an image file format handler will accept string data for. If you specify both-dataand-file, the-fileoption wins, periodt.-format {format-name ?option value ...?}β This tells Tk the name of the file format for the data you gave with-dataor-file, plus any optional arguments to pass to the format handler. Note that the value of this option has to be a Tcl list. That means you can skip the braces if the argument is just one word. Also, you can use double quotes instead of braces for quoting. πββοΈ-file nameβnameis the name of a file to read to get data for the photo image. The file format has to be one that an image file format handler can read. π-gamma valueβ This says the colors allocated to display this image in a window should be corrected for a non-linear display using the given gamma exponent value. (The intensity from most CRT displays is pretty much a power function of the input value; gamma is the exponent and it's usually around 2.) The value you give must be greater than zero. The default is one (no correction). Generally, values greater than one make the image lighter, and values less than one make it darker. π-height numberβ This sets the height of the image in pixels. It's mainly useful when you want to build up the image piece by piece. A value of zero (the default) lets the image expand or shrink vertically to fit whatever data is stored in it. 2 π-metadata metadataβ This sets the metadata dictionary of the image. 2 Additional keys can be 2 set inside the metadata dictionary if image data is 2 processed because of-fileor-dataoptions and the driver outputs 2 any metadata keys. Check out the METADATA DICTIONARY section below. π-palette palette-specβ This sets the resolution of the color cube allocated for displaying the image, which decides how many colors get used from the colormaps of the windows where it's shown. Thepalette-specstring can be either a single decimal number (the number of shades of gray to use) or three decimal numbers separated by slashes (/) β that's the number of shades of red, green, and blue respectively. If you use the first form (just one number), the image will be displayed in monochrome (aka grayscale). π¨-width numberβ This sets the width of the image in pixels. Like-height, it's mainly useful when you're building the image piece by piece. A value of zero (the default) lets the image expand or shrink horizontally to fit the data stored in it. π
IMAGE COMMAND π
When a photo image gets created, Tk also makes a new command with the same name as the image. You can use this command to do all sorts of operations on the image. The general form is:
imageName option ?arg ...?
The option and the args decide exactly what the command does.
Those options that write data to the image will generally make the image bigger if needed to fit the data β unless you've set non-zero values for the -width and/or -height configuration options, in which case the width and/or height (respectively) won't change. π«π
Here are the commands you can use with photo images:
imageName blankβ Blanks the image: sets the whole thing to have no data, so it shows up as transparent, and whatever window it's in will show through. The metadata dict of the image does not change. π«₯imageName cget optionβ Returns the current value of the configuration option given byoption.optioncan be any of the values accepted by theimage create photocommand. πimageName configure ?option? ?value option value ...?β Query or modify the configuration options for the image. If you don't specify anoption, it returns a list describing all the available options forimageName(checkTk_ConfigureInfofor the format of that list). If you specify anoptionwith novalue, you get a list describing that one named option (this list will match the corresponding sublist from the full list). If you give one or more option-value pairs, the command modifies those options to the given values and returns an empty string.optioncan be any of the values accepted by theimage create photocommand. Note that 2 setting the-metadataoption without any other option will not 2 invoke the image format driver to recreate the bitmap. π οΈimageName copy sourceImage ?option value(s) ...?β Copies a region from the image calledsourceImage(which has to be a photo image) to the image calledimageName, possibly with pixel zooming and/or subsampling. If you don't give any options, this command copies the wholesourceImageintoimageName, starting at coordinates(0,0)inimageName. These options are available:-from x1 y1 x2 y2β Specifies a rectangular sub-region of the source image to copy.(x1,y1)and(x2,y2)are diagonally opposite corners of the rectangle. If you don't givex2andy2, the default is the bottom-right corner of the source image. The pixels copied include the left and top edges of the rectangle but not the bottom or right edges. If you don't give-from, the default is the whole source image. π¦-to x1 y1 x2 y2β Specifies a rectangular sub-region of the destination image to affect.(x1,y1)and(x2,y2)are diagonally opposite corners. If you don't givex2andy2, the default is(x1,y1)plus the size of the source region (after subsampling and zooming, if any). If you do givex2andy2, the source region will be replicated if needed to fill the destination region in a tiled way. π§©-shrinkβ Says the size of the destination image should be reduced if necessary so that the region being copied into is at the bottom-right corner of the image. This option won't affect the width or height of the image if you've set a non-zero value for the-widthor-heightconfiguration option, respectively. π-zoom x yβ Says the source region should be magnified by a factor ofxin the X direction andyin the Y direction. If you don't givey, it defaults to the same asx. With this, every pixel in the source image becomes a block ofxxypixels in the destination image, all the same color.xandymust be greater than 0. π-subsample x yβ Says the source image should be reduced in size by using only everyxth pixel in the X direction andyth pixel in the Y direction. Negative values will flip the image about the Y or X axes, respectively. If you don't givey, it defaults to the same asx. π-compositingrule ruleβ Specifies how transparent pixels in the source image get combined with the destination image. When the compositing rule isoverlay, the old contents of the destination image stay visible, like the source image was printed on transparent film and placed on top. When the compositing rule isset, the old contents of the destination image are thrown away and the source image is used as-is. The default compositing rule isoverlay. ποΈ
πΈ imageName data ?option value(s) ...?
okay so this one hands you back the actual image data, but as a string π and the format of that string is entirely up to whichever format handler is doing the work. By default you get a human-readable format β a list of lists of pixel data β but you can swap that out with the -format option. Peep IMAGE FORMATS below for the deets. Here's what you can throw in:
-backgroundcolor β if you pass this color, the data will not contain any transparency information. Every transparent pixel gets replaced by the color you specified. π¨-format{format-name ?option value ...?} β tells it the name of the image file format handler to use, plus optionally some arguments for that handler. Specifically, this subcommand searches for the first handler whose name matches an initial substring of format-name and which can actually write a string containing this image data. If you don't give this option, it uses the default format: a list (one element per row) of lists (one element per pixel/column) of colors in#rrggbbformat (see IMAGE FORMATS below). Lowkey important: the value of this option must be a Tcl list. That means you can drop the braces if the argument is only one word, and you can use double quotes instead of braces for quoting. β¨-fromx1 y1 x2 y2 β picks a rectangular region of imageName to return. If you only give x1 and y1, the region stretches from (x1,y1) all the way to the bottom-right corner of imageName. If you give all four coords, they're diagonally opposite corners of the rectangle β including x1,y1 and excluding x2,y2. Default, if you don't give this option, is the whole entire image. πΌοΈ-grayscaleβ if you specify this, the data will not contain color information. Every pixel gets transformed into grayscale. π©Ά-metadatametadata β the image format handler may use metadata that gets included in the returned data string. The metadata you specify is passed to the driver for inclusion in the data. If you don't give a-metadataoption, the current metadata of the image is used instead. π
π imageName get x y ?-withalpha?
Returns the color of the pixel at coordinates (x,y) as a list of three integers between 0 and 255, representing the red, green and blue components respectively. And if you tack on the -withalpha option, the returned list gets a fourth element β the alpha value of the pixel as an integer between 0 and 255. π
π¦ imageName put data ?option value(s) ...?
Sets pixels in imageName to the data you handed over. This command goes through the list of image file format handlers looking for one that can interpret the data in data, and then reads the image encoded within into imageName (the destination image). See IMAGE FORMATS below for details on formats for image data. Options you can give:
-format{format-name ?option value ..?} β specifies the format of the image data in data, and optionally arguments to pass to the format handler. Specifically, only image file format handlers whose names begin with format-name will be used while searching for an image data format handler to read the data. Note that the value of this option must be a Tcl list β so braces can be omitted if the argument has only one word, and double quotes can be used instead of braces for quoting. β¨-metadatametadata β the metadata you specify gets passed to the image format driver when interpreting the data. Careful though: the current metadata of the image is not passed to the format driver and is not changed by this command. π-tox1 y1 ?x2 y2? β gives the coordinates of the top-left corner (x1,y1) of the region of imageName where the image data gets copied into. Default position is (0,0). If you give x2,y2 and the data isn't big enough to cover the rectangle specified by this option, the image data extracted will be tiled so it covers the whole destination rectangle. And if the region you specified is smaller than the supplied data, the extra data is silently discarded. π Also note: if data specifies a single color value, then a region extending to the bottom-right corner represented by (x2,y2) gets filled with that color. π¨
π§ imageName read filename ?option value(s) ...?
Reads image data from the file named filename into the image. This command first searches the list of image file format handlers for one that can interpret the data in filename, and then reads the image in filename into imageName (the destination image). Options:
-format{format-name ?option value ..?} β specifies the format of the image data in filename, plus optionally additional options for the format handler. Specifically, only image file format handlers whose names begin with format-name will be used while searching for an image data format handler to read the data. Note that the value of this option must be a Tcl list β braces can be omitted if the argument has only one word, and double quotes work instead of braces for quoting. β¨-fromx1 y1 x2 y2 β specifies a rectangular sub-region of the image file data to copy into the destination image. If you only give x1 and y1, the region stretches from (x1,y1) to the bottom-right corner of the image in the image file. If you give all four coordinates, they specify diagonally opposite corners of the region. Default, if this option isn't specified, is the whole image in the image file. πΌοΈ-metadatametadata β the metadata you specify gets passed to the image format driver when interpreting the data. Heads up: the current metadata of the image is not passed to the format driver and is not changed by this command. π-shrinkβ if you pass this, the size of imageName gets reduced, if necessary, so that the region the image file data is read into sits at the bottom-right corner of imageName. This option won't affect the width or height of the image if the user has specified a non-zero value for the-widthor-heightconfiguration option, respectively. π«Ά-tox y β specifies the coordinates of the top-left corner of the region of imageName into which data from filename is read. Default is (0,0). π
π imageName redither
The dithering algorithm used when displaying photo images propagates quantization errors from one pixel to its neighbors. So if the image data for imageName gets supplied in pieces, the dithered image might not be exactly correct π Normally the difference is not noticeable, but if it is a problem, this command can be used to recalculate the dithered image in each window where the image is displayed. π₯
π imageName transparency subcommand ?arg ...?
Lets you examine and manipulate the transparency information in the photo image. There are a few subcommands available:
imageName transparency get x y ?-alpha?β returns true if the pixel at (x,y) is fully transparent, false otherwise. If you pass the-alphaoption, it returns the alpha value of the pixel instead, as an integer in the range 0 to 255. πimageName transparency set x y newVal ?-alpha?β changes the transparency of the pixel at (x,y) to newVal. If no additional option is passed, newVal is interpreted as a boolean, and the pixel is made fully transparent if that value is true, fully opaque otherwise. If the-alphaoption is passed, newVal is interpreted as an integral alpha value for the pixel, which must be in the range 0 to 255. β¨
π imageName write filename ?option value(s) ...?
Writes image data from imageName to a file named filename. Options:
-backgroundcolor β if you pass this color, the data will not contain any transparency information. Every transparent pixel gets replaced by the color you specified. π¨-format {format-name ?option value ...?}β okay bestie, this one tells the write command which image file format handler is gonna do the actual writing, and you can sneak options in for the handler too π Specifically, it goes hunting for the first handler whose name matches an initial substring of format-name and that can actually write an image file. No-format? Then it guesses from the file extension. Can't figure that out either? Then it just grabs the first handler that has write-the-image-file capability, periodt. π
β οΈ Heads up: the value here has to be a Tcl list. Which is lowkey good news, because it means you can drop the braces if the argument is only one word. And instead of braces you can also use double quotes for quoting. No cap. β¨
-from x1 y1 x2 y2β this is your little crop-y moment πΈ it specifies a rectangular region of imageName to be written out to the image file. Give it justx1andy1and the region stretches from (x1,y1) all the way to the bottom-right corner of imageName. Give it all four coordinates and they're the diagonally opposite corners of the rectangle. Not giving it at all? Default is the whole image, iconic behavior π¦-grayscaleβ the moment you use this, your data is not gonna contain color information. All the pixel data gets transformed into grayscale. It's giving black and white film era, it's giving moody aesthetic π€-metadata metadataβ the image format handler may use metadata to be included in the written file π Whatever metadata you specify gets passed to the driver so it can include it in the file. And if you don't give a-metadataoption at all? Then the current metadata of the image is used. Simple as that, bestie π
π IMAGE FORMATS π
okay so bestie, the photo image code was built specifically so that new image file format handlers can be added whenever, no drama. it keeps a whole little list of these handlers, and you add one by registering it with a call to Tk_CreatePhotoImageFormat. the standard Tk distribution rolls up with handlers for PPM/PGM, PNG, GIF and (read-only, so no writing, we respect boundaries) SVG formats, plus the default handler that encodes/decodes image data in a human readable form. and they all justβ¦ show up automatically on initialization. iconic behaviour honestly. β¨
when you're reading an image file, or processing string data you gave with the -data configuration option, the photo image code goes down the list and invokes each handler in turn until one of them claims it can read that data. usually that finds the right one first try, no cap. but if it doesn't? you can hand it a format name with the -format option and be like "no, this one." in that case, the photo image code tries every handler whose name begins with the string you gave -format β and the comparison is case-insensitive, she's chill like that. so if you specify -format gif, then a handler named GIF87 or GIF89 might get invoked, but a handler named JPEG may not (assuming those handlers had been registered, ofc).
writing image data to a file works a lil differently with -format: the string value you give must begin with the complete name of the requested handler, and then it may contain additional info after that, which the handler can use β like, say, to pick which variant of the formats it supports you want. π
heads up bestie: not all image handlers may support writing transparency data to a file, even where the target image format does. the format can do it, the handler might just ghost you. π
π THE DEFAULT IMAGE HANDLER π
the default image handler cannot be used to read or write data from/to a file. nope. its sole purpose is to encode and decode image data in string form, in a clear text, human readable form. it's the vibes-only handler.
the imageName data subcommand uses this handler when no other format is specified. and when you're reading image data from a string with imageName put or the -data option, the default handler gets treated exactly like all the other handlers. no special treatment, she's humble. π
image data in the default string format is a (top-to-bottom) list of scan-lines, with each scan-line being a (left-to-right) list of pixel data. every scan-line has the same length β no chaotic uneven energy here. the color, and optionally the alpha value, of each pixel is specified in any of the forms described down in the COLOR FORMATS section below. β¬οΈ
πΈ FORMAT SUBOPTIONS πΈ
image formats may support sub-options, and you specify them by adding extra words in the value of the -format option. these suboptions can change how image data gets read from or written to a file or a string. what options exist and what they do is entirely up to the format handler β the built-in ones support these:
π§ default -colorformat formatType
this one is allowed when writing image data to a string with imageName data. it specifies the format to use for the color string of each pixel. formatType may be one of:
rgbβ encode pixel data in the form#RRGGBBrgbaβ encode pixel data in the form#RRGGBBAAlistβ encode pixel data as a list with four elements
see COLOR FORMATS below for the details. the default is rgb.
π¦ gif -index indexValue
this one kicks in when reading image data from a file. when parsing a multi-part GIF image, Tk normally only accesses the first image (rude, there are others). by giving the -index sub-option, the indexValue'th value may be used instead. indexValue must be an integer from 0 up to the number of image parts in the GIF data. π―
π png -alpha alphaValue
this one has effect when reading image data from a file. it specifies an additional alpha filtering for the overall image, which lets the background the image is displayed on show through. heads up, this usually also has the effect of desaturating the image. alphaValue must be between 0.0 and 1.0.
π svg -dpi dpiValue -scale scaleValue -scaletowidth width -scaletoheight height
okay this one's got a whole squad of params, let's go one by one:
dpiValueis used in conversion between given coordinates and screen resolution. the value must be greater than0and the default value is96.scaleValueis used to scale the resulting image. the value must be greater than0and the default value is1.widthandheightare the width or height that the image will be adjusted to.
only one parameter among-scale,-scaletowidthand-scaletoheightcan be given at a time, and the aspect ratio of the original image is always preserved. no squishing. we don't do that here.
the svg format supports a wide range of SVG features, but the full SVG standard is not available β for instance the 'text' feature is missing and silently ignored when reading the SVG data. (silently. justβ¦ not telling you. π) the supported SVG features are:
elements:
g, path, rect, circle, ellipse, line, polyline, polygon,
linearGradient, radialGradient, stop, defs, svg, style
attributes:
width, height, viewBox, preserveAspectRatio with none,
xMin, xMid, xMax, yMin, yMid, yMax, slice
gradient attributes:
gradientUnits with objectBoundingBox, gradientTransform,
cx, cy, r fx, fy x1, y1, x2, y2 spreadMethod with pad,
reflect or repeat, xlink:href
poly attributes:
points
line attributes:
x1, y1, x2, y2
ellipse attributes:
cx, cy, rx, ry
circle attributes:
cx, cy, r
rectangle attributes:
x, y, width, height, rx, ry
path attributes:
d with m, M, l, L, h, H, v, V, c, C, s, S, q, Q, t, T, a,
A, z, Z
style attributes:
display with none, visibility, hidden, visible, fill with
nonzero and evenodd, opacity, fill-opacity, stroke,
stroke-width, stroke-dasharray, stroke-dashoffset, stroke-
opacity, stroke-linecap with butt, round and square,
stroke-linejoin with miter, round and bevel, stroke-
miterlimit fill-rule, font-size, transform with matrix,
translate, scale, rotate, skewX and skewY, stop-color,
stop-opacity, offset, id, class
currently only SVG images reading and conversion into (pixel-based format) photos is supported: Tk does not (yet) support bundling photo images in SVG vector graphics. someday bestie. someday. π
π COLOR FORMATS π
the default image handler can represent/parse the color and alpha values of a pixel in any of the formats listed below. if a color format doesn't contain transparency info, full opacity is just assumed. the available color formats are:
- The empty string β interpreted as full transparency, and the color value is undefined. (a little mysterious, a little ethereal, love that for her. β¨)
- Any value accepted by
Tk_GetColor, optionally followed by an alpha suffix. the alpha suffix may be one of:@Aβ the alpha valueAmust be a fractional value in the range0.0(fully transparent) to1.0(fully opaque).#Xβ the alpha valueXis a hexadecimal digit that specifies an integer alpha value in the range0(fully transparent) to255(fully opaque). this is expanded in range from 4 bits wide to 8 bits wide by multiplication by0x11.#XXβ the alpha valueXXis passed as two hexadecimal digits that specify an integer alpha value in the range0(fully transparent) to255(fully opaque).
- A Tcl list with three or four integers in the range
0to255, specifying the values for the red, green, blue and (optionally) alpha channels respectively. #RGBAformat: a#followed by four hexadecimal digits, where each digit is the value for the red, green, blue and alpha channels respectively. each digit will be expanded internally to 8 bits by multiplication by0x11.#RRGGBBAAformat:#followed by eight hexadecimal digits, where each pair of subsequent digits represents the value for the red, green, blue and alpha channels respectively.
π¨ COLOR ALLOCATION π¨
okay so when a photo image gets displayed in a window, the photo image code is out here allocating colors to actually show it, and it dithers the image if it has to β basically it's doing its best to make a reasonable approximation using whatever colors are available. The colors get allocated as a color cube, meaning the number of colors allocated is the product of the number of shades of red, green and blue.
Normally the number of colors allocated is chosen based on the depth of the window. Like, in an 8-bit PseudoColor window, the photo image code will attempt to allocate seven shades of red, seven shades of green and four shades of blue, for a total of 198 colors. In a 1-bit StaticGray (monochrome) window, it allocates two colors: black and white. In a 24-bit DirectColor or TrueColor window, it allocates 256 shades each of red, green and blue. And fortunately, because of the way pixel values can be combined in DirectColor and TrueColor windows, this only requires 256 colors to be allocated. If not all of the colors can be allocated, the photo image code reduces the number of shades of each primary color and tries again.
You can exercise some control over the number of colors a photo image uses with the -palette configuration option. If this option is used, it specifies the maximum number of shades of each primary color to try to allocate. It can also be used to force the image to be displayed in shades of gray, even on a color display, by giving a single number rather than three numbers separated by slashes.
ποΈ METADATA DICTIONARY ποΈ
Each image has a metadata dictionary property. This dictionary is not relevant to the bitmap representation of the image, but it may contain additional information like resolution or comments. Image format drivers may output metadata when image data is parsed, or may use metadata to be included in image files or formats.
π METADATA KEYS (MULTIPLE FORMATS) π
Each image format driver supports an individual set of metadata dictionary keys. Predefined keys are:
DPIβ Horizontal image resolution in DPI as a double value. Supported by formatpng.aspectβ Aspect ratio horizontal divided by vertical as double value. Supported by formatsgifandpng.commentβ Image text comment. Supported by formatsgifandpng.
It is valid to set any key in the metadata dict. A format driver will ignore keys that it does not handle.
ποΈ METADATA KEYS FOR ANIMATED GIF INFORMATION ποΈ
The following metadata keys are reported when reading a gif format file. They are typically used in conjunction with the -index option of an animated gif file to properly display the subimage sequence. The options are linked to each subimage selected by -index.
delay timetime β Update delay time in 10ms units. This key is only present if the delay time is not 0.disposal methodmethod β Disposal method of the preceeding image, if given for the current image. Possible values are: do not dispose, restore to background color, restore to previous.user interactionbool β The key is present with a value of 1, if user interaction is specified. Otherwise, the key is not present.update regionX0, Y0, width, height β Update region of the current subimage, if subimage has not the same size as the full image. The pixel outside of this box are all fully transparent.
π CREDITS π
The photo image type was designed and implemented by Paul Mackerras, based on his earlier photo widget and some suggestions from John Ousterhout.
π EXAMPLE π
Load an image from a file and tile it to the size of a window, which is useful for producing a tiled background:
# These lines should be called once
image create photo untiled -file "theFile.ppm"
image create photo tiled
# These lines should be called whenever .someWidget changes
# size; a <Configure> binding is useful here
set width [winfo width .someWidget]
set height [winfo height .someWidget]
tiled copy untiled -to 0 0 $width $height -shrink
The PNG image loader allows the application of an additional alpha factor during loading, which is useful for generating images suitable for disabled buttons:
image create photo icon -file "icon.png"
image create photo iconDisabled -file "icon.png" \
-format "png -alpha 0.5"
button .b -image icon -disabledimage iconDisabled
Create a green box with a simple shadow effect
image create photo foo
# Make a simple graduated fill varying in alpha for the shadow
for {set i 14} {$i > 0} {incr i -1} {
set i2 [expr {$i + 30}]
foo put [format black#%x [expr {15-$i}]] -to $i $i $i2 $i2
}
# Put a solid green rectangle on top
foo put #F080 -to 0 0 30 30
π SEE ALSO π
π·οΈ KEYWORDS π·οΈ
photo, image, color
That's the whole page, bestie π source/version footer energy is Tk 4.0, page photo(3tk) β and that's on periodt. β¨
π¦ where this page comes from
- ubuntu resolute: tk9.0-doc 9.0.3-1
- ubuntu stonking: tk9.0-doc 9.0.4-1
- Copyright (c) 1994 The Australian National University
- Copyright (c) 1994-1997 Sun Microsystems, Inc
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms