1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
runewidth "github.com/mattn/go-runewidth"
_ "golang.org/x/image/bmp"
"golang.org/x/image/draw"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
"golang.org/x/term"
)
var (
x = flag.Int("x", 15, "set image width in columns")
y = flag.Int("y", 0, "set image height in rows")
)
func isDir(filename string) (bool, error) {
stat, err := os.Stat(filename)
if err != nil {
return false, err
}
return stat.IsDir(), nil
}
func isLink(filename string) (bool, error) {
stat, err := os.Lstat(filename)
if err != nil {
return false, err
}
return stat.Mode().Type() == fs.ModeSymlink, nil
}
var errNotAnImage = errors.New("not an image")
type notAnImageError struct {
error
}
func (e *notAnImageError) Is(err error) bool {
return err == errNotAnImage
}
func load(filename string) (image.Image, error) {
file := os.Stdin
if filename != "-" {
var err error
file, err = os.Open(filename)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
if isLink, _ := isLink(filename); isLink {
return nil, ¬AnImageError{err}
}
}
return nil, err
}
defer file.Close()
}
img, _, err := image.Decode(file)
if err != nil {
return nil, ¬AnImageError{fmt.Errorf("decode %q: %s", filename, err)}
}
return img, nil
}
func printImg(img image.Image, cols, lines int) (string, int) {
// Try not to stretch the image.
if lines <= 0 || img.Bounds().Dy()*cols <= img.Bounds().Dx()*lines*5/2 {
lines = img.Bounds().Dy() * cols / (img.Bounds().Dx() * 5 / 2)
} else {
cols = img.Bounds().Dx() * lines * 5 / 2 / img.Bounds().Dy()
}
if lines == 0 || cols == 0 {
return "", 0
}
dst := image.NewRGBA(image.Rect(0, 0, cols, 2*lines))
draw.BiLinear.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Over, nil)
s := new(strings.Builder)
for y := 0; y < 2*lines; y += 2 {
if y > 0 {
fmt.Fprintln(s)
}
for x := 0; x < cols; x++ {
hiR, hiG, hiB, _ := dst.At(x, y).RGBA()
loR, loG, loB, _ := dst.At(x, y+1).RGBA()
fmt.Fprintf(s, "\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dmâ–€",
hiR>>8, hiG>>8, hiB>>8,
loR>>8, loG>>8, loB>>8)
}
fmt.Fprint(s, "\033[39m\033[49m")
}
return s.String(), cols
}
type img struct {
s string
width int
filename string
}
func compositeImages(w io.Writer, images []img, imageWidth, imagesPerRow int) {
for row := range slices.Chunk(images, imagesPerRow) {
rowLines := make([][]string, len(row))
names := make([][]string, len(row))
for i, img := range row {
rowLines[i] = strings.Split(img.s, "\n")
names[i] = strings.Split(runewidth.Wrap(img.filename, imageWidth), "\n")
}
maxLen := 0
for imgIdx, img := range rowLines {
maxLen = max(maxLen, len(img)+len(names[imgIdx]))
}
for i := 0; i < maxLen; i++ {
if i > 0 {
fmt.Fprintln(w)
}
for imgIdx, img := range rowLines {
if imgIdx > 0 {
fmt.Fprint(w, " ")
}
if i < len(img) {
fmt.Fprintf(w, "%s%*s", img[i], max(imageWidth-row[imgIdx].width, 0), "")
} else if i < len(img)+len(names[imgIdx]) {
fmt.Fprintf(w, "%s", runewidth.FillRight(names[imgIdx][i-len(img)], imageWidth))
} else {
fmt.Fprintf(w, "%*s", imageWidth, "")
}
}
}
fmt.Fprintln(w)
}
}
func thumbnailFiles(w io.Writer, cols, lines, imagesPerRow int, args []string) error {
var images []img
for _, arg := range args {
image, err := load(arg)
if err != nil {
if errors.Is(err, errNotAnImage) {
continue
}
return err
}
imageString, width := printImg(image, cols, lines)
images = append(images, img{imageString, width, filepath.Base(arg)})
}
compositeImages(w, images, cols, imagesPerRow)
return nil
}
func readDir(d string) ([]string, error) {
files, err := os.ReadDir(d)
if err != nil {
return nil, err
}
filenames := make([]string, len(files))
for i, f := range files {
filenames[i] = filepath.Join(d, f.Name())
}
return filenames, nil
}
func thumbnailer(args []string) error {
cols := *x
lines := *y
if cols <= 0 {
return fmt.Errorf("-x must be greater than 0")
}
termCols, _, err := term.GetSize(1)
if err != nil {
return fmt.Errorf("terminal size: %s", err)
}
imagesPerRow := termCols / (cols + 1)
var files, dirs []string
switch len(args) {
case 0:
files, err = readDir(".")
if err != nil {
return err
}
case 1:
arg := args[0]
isDir, err := isDir(arg)
if err != nil {
return err
}
if isDir {
files, err = readDir(arg)
if err != nil {
return err
}
} else {
files = []string{arg}
}
default:
for _, arg := range args {
isDir, err := isDir(arg)
if err != nil {
return err
}
if isDir {
dirs = append(dirs, arg)
} else {
files = append(files, arg)
}
}
}
w := bufio.NewWriter(os.Stdout)
defer w.Flush()
if err := thumbnailFiles(w, cols, lines, imagesPerRow, files); err != nil {
return err
}
if len(files) > 0 && len(dirs) > 0 {
fmt.Fprintln(w)
}
for i, d := range dirs {
if i > 0 {
fmt.Fprintln(w)
}
fmt.Fprintf(w, "%s:\n", d)
dirFiles, err := readDir(d)
if err != nil {
return err
}
if err := thumbnailFiles(w, cols, lines, imagesPerRow, dirFiles); err != nil {
return err
}
}
return nil
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: thumbnailer [FILE]...\n")
}
flag.Parse()
if err := thumbnailer(flag.Args()); err != nil {
fmt.Fprintf(os.Stderr, "Failed: %s\n", err)
os.Exit(1)
}
}
|