From 5924ab4508d90f074157888899ac52c2af57090a Mon Sep 17 00:00:00 2001 From: Rose Hogenson Date: Mon, 17 Mar 2025 20:22:28 -0700 Subject: Improve usage --- README.md | 3 +++ icat.go | 46 +++++++++++++++++++++++++++------------------- 2 files changed, 30 insertions(+), 19 deletions(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..0dc67b9 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# The worst terminal image viewer + +seriously just use img2sixel diff --git a/icat.go b/icat.go index 01f0400..4bcfb45 100644 --- a/icat.go +++ b/icat.go @@ -2,6 +2,8 @@ package main import ( "bufio" + "errors" + "flag" "fmt" "image" _ "image/jpeg" @@ -12,8 +14,6 @@ import ( "golang.org/x/term" ) -var stdout = bufio.NewWriter(os.Stdout) - func load(filename string) (image.Image, error) { file := os.Stdin if filename != "-" { @@ -33,12 +33,7 @@ func load(filename string) (image.Image, error) { return img, nil } -func printImg(filename string, cols, lines int) error { - img, err := load(filename) - if err != nil { - return err - } - +func printImg(img image.Image, cols, lines int) error { // Try not to stretch the image. if img.Bounds().Dy()*cols <= img.Bounds().Dx()*lines*5/2 { lines = img.Bounds().Dy() * cols / (img.Bounds().Dx() * 5 / 2) @@ -49,42 +44,55 @@ func printImg(filename string, cols, lines int) error { dst := image.NewRGBA(image.Rect(0, 0, cols, 2*lines)) draw.BiLinear.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Over, nil) + w := bufio.NewWriter(os.Stdout) + defer w.Flush() for y := 0; y < 2*lines; y += 2 { 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(stdout, "\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▀", + fmt.Fprintf(w, "\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.Fprintln(stdout, "\033[49m") + fmt.Fprintln(w, "\033[49m") } - fmt.Fprint(stdout, "\033[39m") + fmt.Fprint(w, "\033[39m") return nil } func icat(args []string) error { + if len(args) == 0 { + return errors.New("missing positional argument") + } + if len(args) > 1 { + return errors.New("too many positional arguments") + } + file := args[0] + cols, lines, err := term.GetSize(1) if err != nil { return fmt.Errorf("terminal size: %s", err) } lines-- // Leave a line for the status bar. - if len(args) == 0 { - args = []string{"-"} + img, err := load(file) + if err != nil { + return err } - defer stdout.Flush() - for _, f := range args { - if err := printImg(f, cols, lines); err != nil { - return err - } + if err := printImg(img, cols, lines); err != nil { + return err } return nil } func main() { - if err := icat(os.Args[1:]); err != nil { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "Usage: icat FILE\n") + } + flag.Parse() + + if err := icat(flag.Args()); err != nil { fmt.Fprintf(os.Stderr, "Failed: %s\n", err) os.Exit(1) } -- cgit v1.3.1