repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

pico / shared / storage
Eric Bower · 31 Jan 24

ratio.go

 1package storage
 2
 3import (
 4	"fmt"
 5	"strconv"
 6	"strings"
 7)
 8
 9type Ratio struct {
10	Width  int
11	Height int
12}
13
14func GetRatio(dimes string) (*Ratio, error) {
15	if dimes == "" {
16		return nil, nil
17	}
18
19	// bail if we detect imgproxy options
20	if strings.Contains(dimes, ":") {
21		return nil, nil
22	}
23
24	// dimes = x250 -- width is auto scaled and height is 250
25	if strings.HasPrefix(dimes, "x") {
26		height, err := strconv.Atoi(dimes[1:])
27		if err != nil {
28			return nil, err
29		}
30		return &Ratio{Width: 0, Height: height}, nil
31	}
32
33	// dimes = 250x -- width is 250 and height is auto scaled
34	if strings.HasSuffix(dimes, "x") {
35		width, err := strconv.Atoi(dimes[:len(dimes)-1])
36		if err != nil {
37			return nil, err
38		}
39		return &Ratio{Width: width, Height: 0}, nil
40	}
41
42	// dimes = 250x250
43	res := strings.Split(dimes, "x")
44	if len(res) != 2 {
45		return nil, fmt.Errorf("(%s) must be in format (x200, 200x, or 200x200)", dimes)
46	}
47
48	ratio := &Ratio{}
49	width, err := strconv.Atoi(res[0])
50	if err != nil {
51		return nil, err
52	}
53	ratio.Width = width
54
55	height, err := strconv.Atoi(res[1])
56	if err != nil {
57		return nil, err
58	}
59	ratio.Height = height
60
61	return ratio, nil
62}