a little more flexibility with scaling images by url

This commit is contained in:
2017-07-02 23:30:07 -07:00
parent 733594be70
commit 80e391d317
2 changed files with 39 additions and 7 deletions
+39 -6
View File
@@ -66,6 +66,25 @@ func (ms *MediaSource) receiveNewMedia(name string, r io.Reader) error {
type Media struct {
Type string
Name string
Size image.Rectangle
}
func (ms *MediaSource) Size(name string) (image.Rectangle, error) {
f, err := os.Open(name)
if err != nil {
return image.ZR, err
}
defer f.Close()
cfg, _, err := image.DecodeConfig(f)
if err != nil {
return image.ZR, err
}
width := cfg.Width
height := cfg.Height
return image.Rect(0, 0, width, height), nil
}
func (ms *MediaSource) ThumbMax(m Media, maxDim int) (string, image.Rectangle, error) {
@@ -116,9 +135,11 @@ func (ms *MediaSource) HasThumb(m Media, size image.Rectangle) bool {
}
func (ms *MediaSource) ByName(name string) *Media {
size, _ := ms.Size(path.Join(ms.StorageDir, name))
return &Media{
Type: "image",
Name: name,
Size: size,
}
}
@@ -280,14 +301,14 @@ func (ch *CaddyHugo) serveMediaPage(w http.ResponseWriter, r *http.Request) (int
}
var (
sizeString = regexp.MustCompile(`([0-9]*)x([0-9]*)`)
sizeString = regexp.MustCompile(`([0-9]*)(x)?([0-9]*)`)
)
func parseSizeString(str string) (image.Rectangle, error) {
func parseSizeString(str string, actual image.Rectangle) (image.Rectangle, error) {
var err = fmt.Errorf("expected a size string {width}x{height}, saw %q", str)
strs := sizeString.FindStringSubmatch(str)
if len(strs) < 3 {
if len(strs) < 4 {
return image.ZR, err
}
@@ -301,13 +322,25 @@ func parseSizeString(str string) (image.Rectangle, error) {
}
}
if strs[2] != "" {
h, strconvErr = strconv.Atoi(strs[2])
if strs[3] != "" {
h, strconvErr = strconv.Atoi(strs[3])
if strconvErr != nil {
return image.ZR, err
}
}
if strs[2] != "x" {
// w was the only dimension given, so set it to the greater dimension
// of the actual image size
if actual.Dx() > actual.Dy() {
w = w
h = 0
} else {
h = w
w = 0
}
}
return image.Rect(0, 0, w, h), nil
}
@@ -326,7 +359,7 @@ func (ch *CaddyHugo) serveMedia(w http.ResponseWriter, r *http.Request) (int, er
if len(segs) >= 4 && len(segs) > 2 {
var err error
size, err = parseSizeString(segs[len(segs)-2])
size, err = parseSizeString(segs[len(segs)-2], m.Size)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return 400, nil