~dricottone/image2ascii

ref: 0eb5e7a0c70c5c94b3fe10ccdfcaed8b54442464 image2ascii/convert/resize.go -rw-r--r-- 1.7 KiB
0eb5e7a0 — qeesung Update the example 6 years ago
                                                                                
c6c0ddbf qeesung
9b483cdb qeesung
55dcbb9f qeesung
9b483cdb qeesung
55dcbb9f qeesung
9b483cdb qeesung
55dcbb9f qeesung
9b483cdb qeesung
49547468 qeesung
c6c0ddbf qeesung
9b483cdb qeesung
55dcbb9f qeesung
c6c0ddbf qeesung
9b483cdb qeesung
49547468 qeesung
9b483cdb qeesung
65420f04 qeesung
9b483cdb qeesung
49547468 qeesung
9b483cdb qeesung
55dcbb9f qeesung
49547468 qeesung
c6c0ddbf qeesung
55dcbb9f qeesung
c6c0ddbf qeesung
55dcbb9f qeesung
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
package convert

import (
	"github.com/mattn/go-isatty"
	"github.com/nfnt/resize"
	terminal "github.com/wayneashleyberry/terminal-dimensions"
	"image"
	"log"
	"os"
	"runtime"
)

// ScaleImage resize the convert to expected size base on the convert options
func ScaleImage(image image.Image, options *Options) (newImage image.Image) {
	sz := image.Bounds()
	ratio := options.Ratio
	newHeight := sz.Max.X
	newWidth := sz.Max.Y

	if options.ExpectedWidth != -1 {
		newWidth = options.ExpectedWidth
	}

	if options.ExpectedHeight != -1 {
		newHeight = options.ExpectedHeight
	}

	// use the ratio the scale the image
	if options.ExpectedHeight == -1 && options.ExpectedWidth == -1 && ratio != 1 {
		newWidth = int(float64(sz.Max.X) * ratio)
		newHeight = int(float64(sz.Max.Y) * ratio * charWidth())
	}

	// fit the screen
	// get the fit the screen size
	if ratio == 1 &&
		options.ExpectedWidth == -1 &&
		options.ExpectedHeight == -1 &&
		options.FitScreen {
		screenWidth, screenHeight := getFitScreenSize()
		newWidth = int(screenWidth)
		newHeight = int(screenHeight)
	}

	newImage = resize.Resize(uint(newWidth), uint(newHeight), image, resize.Lanczos3)
	return
}

// charWidth get the terminal char width on different system
func charWidth() float64 {
	if isWindows() {
		return 0.714
	}
	return 0.5
}

// isWindows check if current system is windows
func isWindows() bool {
	return runtime.GOOS == "windows"
}

// getFitScreenSize get the current terminal screen size
func getFitScreenSize() (newWidth, newHeight uint) {
	if !isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()) {
		log.Fatal("Can not detect the terminal, please disable the '-s fitScreen' option")
	}

	x, _ := terminal.Width()
	y, _ := terminal.Height()

	return x, y
}