Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions internal/image/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"io"
"os"
"strings"

"golang.org/x/term"
)

const (
Expand All @@ -21,9 +23,13 @@ type rgbColor struct {
}

// writeBlocks resizes the image and outputs it as terminal blocks.
func writeBlocks(img image.Image, termWidth, termHeight int) error {
func writeBlocks(img image.Image) error {
trueColor := supportsTrueColor()

termWidth, termHeight, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
return err
}
cols, rows := imageBlockOutputDimensions(img, termWidth, termHeight)

// Each terminal block represents 2 vertical pixels.
Expand All @@ -34,11 +40,11 @@ func writeBlocks(img image.Image, termWidth, termHeight int) error {

// Process the image in blocks (each block = two vertical pixels).
var out bytes.Buffer
for row := 0; row < rows; row++ {
for row := range rows {
topY := row * 2
bottomY := topY + 1

for x := 0; x < cols; x++ {
for x := range cols {
top := pixelToColor(dst.At(x, topY))
var bottom *rgbColor
if bottomY < targetHeight {
Expand Down Expand Up @@ -80,19 +86,10 @@ func imageBlockOutputDimensions(img image.Image, termWidth, termHeight int) (int

// Otherwise calculate appropriate size.
if cols*height <= width*rows {
h := (height * cols) / width / 2
if h < 1 {
h = 1
}
return cols, h
return cols, max((height*cols)/width/2, 1)
}

w := (width * rows) / height
h := rows / 2
if h < 1 {
h = 1
}
return w, h
return (width * rows) / height, max(rows/2, 1)
}

// pixelToColor converts a color.Color into a *rgbColor (or nil if fully transparent).
Expand Down
11 changes: 2 additions & 9 deletions internal/image/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,11 @@ import (
"image"
_ "image/jpeg"
"image/png"
"os"
"strings"

"golang.org/x/image/draw"
_ "golang.org/x/image/tiff"
_ "golang.org/x/image/webp"
"golang.org/x/term"
)

func Render(b []byte) error {
Expand All @@ -22,19 +20,14 @@ func Render(b []byte) error {
}
img = orient(b, img)

termWidth, termHeight, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
return err
}

termWidthPx, termHeightPx, err := getTermSizeInPixels()
if err != nil {
return err
}
if termWidthPx == 0 || termHeightPx == 0 {
// If we're unable to get the terminal dimensions in pixels,
// render the image using blocks.
return writeBlocks(img, termWidth, termHeight)
return writeBlocks(img)
}

switch detectEmulator().Protocol() {
Expand All @@ -43,7 +36,7 @@ func Render(b []byte) error {
case protoKitty:
return writeKitty(img, termWidthPx, termHeightPx)
default:
return writeBlocks(img, termWidth, termHeight)
return writeBlocks(img)
}
}

Expand Down
Loading