Anki/image.go

60 lines
1.1 KiB
Go

package main
import (
"fmt"
"image"
"image/jpeg"
"image/png"
"os"
"path"
"github.com/Lewuathe/gimg/ansi"
"github.com/nfnt/resize"
)
func View(p string) {
in, err := os.Open(p)
if err != nil {
panic(err)
}
defer in.Close()
var src image.Image
switch path.Ext(p) {
case ".jpg", ".jpeg":
src, err = jpeg.Decode(in)
case ".png":
src, err = png.Decode(in)
default:
panic(path.Ext(p))
}
if err != nil {
panic(err)
}
printImage(40, src)
}
func printImage(limit int, image image.Image) {
if image.Bounds().Max.X > image.Bounds().Max.Y {
xmax := image.Bounds().Max.X
ratio := float64(limit) / float64(xmax)
width := uint(float64(xmax) * ratio)
image = resize.Resize(width, 0, image, resize.Bicubic)
} else {
ymax := image.Bounds().Max.Y
ratio := float64(limit) / float64(ymax)
height := uint(float64(ymax) * ratio)
image = resize.Resize(0, height, image, resize.Bicubic)
}
for i := 0; i < image.Bounds().Max.Y; i++ {
for j := 0; j < image.Bounds().Max.X; j++ {
r, g, b, _ := image.At(j, i).RGBA()
r = ansi.To256(r)
g = ansi.To256(g)
b = ansi.To256(b)
ansi.Print(r, g, b)
}
fmt.Printf("\n")
}
}