lib/image.sh

2.2 KB · 87 lines · bash

1#!/usr/bin/env bash
2
3brt_image() {
4 local file="${1:-}"
5 local width=0
6 local height=0
7 local term_w term_h size
8
9 if [[ -z "$file" ]]; then
10 brt_error "Usage: brt -image <file> [-x cols] [-y rows]"
11 brt_info "Renders images in the terminal (chafa, viu, imgcat, or ASCII fallback)"
12 brt_info "Default size fills your terminal; -x/-y set size in character cells"
13 exit 1
14 fi
15
16 shift
17 while [[ $# -gt 0 ]]; do
18 case "$1" in
19 -x) width="$2"; shift 2 ;;
20 -y) height="$2"; shift 2 ;;
21 -w|--width) width="$2"; shift 2 ;;
22 *)
23 brt_error "Unknown option: $1"
24 brt_info "Usage: brt -image <file> [-x cols] [-y rows]"
25 exit 1
26 ;;
27 esac
28 done
29
30 if [[ ! -f "$file" ]]; then
31 brt_error "File not found: ${file}"
32 exit 1
33 fi
34
35 if ! [[ "$width" =~ ^[0-9]+$ && "$height" =~ ^[0-9]+$ ]]; then
36 brt_error "-x and -y must be non-negative integers"
37 exit 1
38 fi
39
40 read -r term_w term_h < <(brt_term_media_size "$width" "$height") || {
41 brt_error "Could not determine image size"
42 exit 1
43 }
44 size="${term_w}x${term_h}"
45
46 brt_info "Rendering ${file} at ${size}..."
47
48 # Kitty terminal
49 if [[ "${TERM:-}" == *kitty* ]] && command -v kitty &>/dev/null; then
50 kitty +kitten icat --transfer-mode=file --align=left --place "${size}@0x0" "$file" 2>/dev/null && return 0
51 fi
52
53 # iTerm2 imgcat
54 if [[ "${TERM_PROGRAM:-}" == "iTerm.app" ]] && command -v imgcat &>/dev/null; then
55 imgcat -W "${term_w}" "$file" && return 0
56 fi
57
58 # chafa — best general terminal renderer
59 if command -v chafa &>/dev/null; then
60 chafa -s "${size}" "$file"
61 return 0
62 fi
63
64 # viu
65 if command -v viu &>/dev/null; then
66 viu -w "$term_w" -h "$term_h" "$file"
67 return 0
68 fi
69
70 # macOS: sips + Python ASCII fallback
71 if command -v sips &>/dev/null && command -v python3 &>/dev/null; then
72 local tmp
73 tmp=$(mktemp).ppm
74 if sips -s format ppm "$file" --out "$tmp" &>/dev/null; then
75 python3 "${BRT_LIB}/media.py" ascii "$tmp" "$term_w" "$term_h"
76 rm -f "$tmp"
77 brt_info "ASCII fallback — install chafa for color: brew install chafa"
78 return 0
79 fi
80 rm -f "$tmp"
81 fi
82
83 brt_error "No image renderer available."
84 brt_info "Install one of: chafa, viu (brew install chafa)"
85 exit 1
86}
87