~dricottone/image2ascii

ref: 49547468910f360ba23ca6cb7da66e8ebecf9b7e image2ascii/convert/convert.go -rw-r--r-- 1.8 KiB
49547468 — qeesung Rewrite the go docs 6 years ago
                                                                                
c3affd9f qeesung
1021c573 qeesung
bc120092 qeesung
1021c573 qeesung
bc120092 qeesung
1021c573 qeesung
49547468 qeesung
1021c573 qeesung
c6c0ddbf qeesung
49547468 qeesung
1021c573 qeesung
49547468 qeesung
c5de7795 qeesung
1021c573 qeesung
c5de7795 qeesung
1021c573 qeesung
c5de7795 qeesung
1021c573 qeesung
49547468 qeesung
1021c573 qeesung
bc120092 qeesung
49547468 qeesung
bc120092 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
// Package convert can convert a image to ascii string or matrix
package convert

import (
	"bytes"
	"github.com/qeesung/image2ascii/ascii"
	"image"
	"image/color"
	"log"
	"os"
)

// Options to convert the image to ASCII
type Options struct {
	Ratio          float64
	ExpectedWidth  int
	ExpectedHeight int
	FitScreen      bool
	Colored        bool
}

// Image2ASCIIMatrix converts a image to ASCII matrix
func Image2ASCIIMatrix(image image.Image, imageConvertOptions *Options) []string {
	// Resize the convert first
	newImage := ScaleImage(image, imageConvertOptions)
	sz := newImage.Bounds()
	newWidth := sz.Max.Y
	newHeight := sz.Max.X
	rawCharValues := make([]string, int(newWidth*newHeight))
	for i := 0; i < int(newWidth); i++ {
		for j := 0; j < int(newHeight); j++ {
			pixel := color.NRGBAModel.Convert(newImage.At(j, i))
			// Convert the pixel to ascii char
			pixelConvertOptions := ascii.NewOptions()
			pixelConvertOptions.Colored = imageConvertOptions.Colored
			rawChar := ascii.ConvertPixelToASCII(pixel, &pixelConvertOptions)
			rawCharValues = append(rawCharValues, rawChar)
		}
		rawCharValues = append(rawCharValues, "\n")
	}
	return rawCharValues
}

// Image2ASCIIString converts a image to ascii matrix, and the join the matrix to a string
func Image2ASCIIString(image image.Image, options *Options) string {
	convertedPixelASCII := Image2ASCIIMatrix(image, options)
	var buffer bytes.Buffer

	for i := 0; i < len(convertedPixelASCII); i++ {
		buffer.WriteString(convertedPixelASCII[i])
	}
	return buffer.String()
}

// ImageFile2ASCIIString converts a image file to ascii string
func ImageFile2ASCIIString(imageFilename string, option *Options) string {
	f, err := os.Open(imageFilename)
	if err != nil {
		log.Fatal(err)
	}

	img, _, err := image.Decode(f)
	if err != nil {
		log.Fatal(err)
	}

	f.Close()
	return Image2ASCIIString(img, option)
}