Image viewer using FFmpeg

dbohdan 2026-11-23: This basic image viewer demonstrates the use of FFmpeg to decode unsupported image formats like AVIF and JPEG XL. Since Tk cannot load them natively, we convert them to PNG on the fly. This conversion depends on a single external FFmpeg binary.

Code

#! /usr/bin/env tclsh
# Image loader and viewer using FFmpeg.
# Copyright (c) 2026 D. Bohdan.
# License: MIT.

package require Tcl 8.6 9

namespace eval ::ffmpeg_image {
    variable version 0.1.0
}


proc ::ffmpeg_image::load path {
    set command [list \
        ffmpeg \
        -hide_banner \
        -loglevel error \
        -i $path \
        -c:v png \
        -f image2pipe \
        pipe:1 \
    ]

    try {
        set ch [open |$command]
        fconfigure $ch -translation binary

        return [read $ch]
    } finally {
        catch { close $ch }
    }
}


oo::class create ::ffmpeg_image::Viewer {
    variable image_index
    variable image_paths

    constructor paths {
        set image_paths $paths
        set image_index 0

        label .lbl
        pack .lbl

        event add <<Quit>> <Key-q> <Key-Q> <Key-Escape>
        bind . <<Quit>> { exit 0 }
        bind . <Key-Left> [namespace code { my update -1 }]
        bind . <Key-Right> [namespace code { my update 1 }]

        my update 0
    }

    method update increment {
        set max [llength $image_paths]
        set image_index [expr { ($image_index + $increment) % $max }]

        set path [lindex $image_paths $image_index]

        set current_image [.lbl cget -image]
        if {$current_image ne {}} {
            rename $current_image {}
        }

        set image_data [::ffmpeg_image::load $path]
        .lbl configure -image [image create photo -data $image_data -format png]

        wm title . [file tail $path]
    }
}


# If this is the main script...
if {[info exists argv0] && ([file tail [info script]] eq [file tail $argv0])} {
    package require Tk

    if {[llength $argv] < 1} {
        puts "usage: [list [file tail [info script]]] image.ext \[image.ext ...\]"
        exit 2
    }

    ::ffmpeg_image::Viewer create image_viewer $argv
}

Test images

See also

Discussion