summaryrefslogtreecommitdiff
path: root/internal/colors/cmyk.go
blob: 30bc290845a7daf316f813b6812da688a4d6441f (plain)
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
package colors

import (
	"fmt"
	"math"
)

type CMYK struct {
	C int // 0-100
	M int // 0-100
	Y int // 0-100
	K int // 0-100
}

func (c CMYK) String() string {
	return fmt.Sprintf("cmyk(%d%%, %d%%, %d%%, %d%%)", c.C, c.M, c.Y, c.K)
}

func (c CMYK) ToPrecise() PreciseColor {
	return PreciseColor{
		R: (1 - float64(c.C)/100) * (1 - float64(c.K)/100),
		G: (1 - float64(c.M)/100) * (1 - float64(c.K)/100),
		B: (1 - float64(c.Y)/100) * (1 - float64(c.K)/100),
	}
}

func (c CMYK) FromPrecise(p PreciseColor) ColorSpace {
	// Extract RGB components from the PreciseColor
	r := p.R
	g := p.G
	b := p.B

	// Calculate the K (key/black) component
	k := 1 - math.Max(math.Max(r, g), b)

	// Avoid division by zero when K is 1 (pure black)
	if k == 1 {
		return CMYK{C: 0, M: 0, Y: 0, K: 100}
	}

	// Calculate the CMY components based on the remaining color values
	cyan := (1 - r - k) / (1 - k)
	magenta := (1 - g - k) / (1 - k)
	yellow := (1 - b - k) / (1 - k)

	// Scale to 0-100 and return
	return CMYK{
		C: int(math.Round(cyan * 100)),
		M: int(math.Round(magenta * 100)),
		Y: int(math.Round(yellow * 100)),
		K: int(math.Round(k * 100)),
	}
}