/
main.go
107 lines (94 loc) · 1.75 KB
/
main.go
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
package main
import (
"bufio"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"github.com/BurntSushi/graphics-go/graphics"
"github.com/mattn/go-sixel"
)
// Reasonable max size, to reduce output
var maxWidth = 1280
var maxHeight = 720
func dump(f *os.File) error {
buf := bufio.NewReader(f)
_, _ = io.Copy(os.Stdout, buf)
return nil
}
func render(filename string) error {
var f *os.File
var err error
if filename != "-" {
f, err = os.Open(filename)
if err != nil {
return err
}
defer f.Close()
} else {
f = os.Stdin
}
if !hasSixel() {
return dump(f)
}
img, _, err := image.Decode(f)
if err != nil {
if err == image.ErrFormat {
f.Close()
f, err = os.Open(filename)
if err != nil {
return err
}
defer f.Close()
return dump(f)
}
return err
}
h, w := img.Bounds().Dy(), img.Bounds().Dx()
if h > maxHeight || w > maxWidth {
rx := float64(w) / float64(maxWidth)
ry := float64(h) / float64(maxHeight)
if rx < ry {
w = int(float64(w) / ry)
h = maxHeight
} else {
h = int(float64(h) / rx)
w = maxWidth
}
tmp := image.NewNRGBA64(image.Rect(0, 0, int(w), int(h)))
err = graphics.Scale(tmp, img)
if err != nil {
return err
}
img = tmp
}
buf := bufio.NewWriter(os.Stdout)
defer buf.Flush()
enc := sixel.NewEncoder(buf)
enc.Dither = true
err = enc.Encode(img)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
return err
}
// FIXME: Detect sixel support
func hasSixel() bool {
return true
}
// FIXME: Support `cat` options like `-vET`, and scratches your arm up
func main() {
if len(os.Args) < 2 {
// Make it cat compatible
_ = render("-")
}
for _, arg := range os.Args[1:] {
err := render(arg)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
}