From 80e391d31758ac26a67a080087492a05a2e0215f Mon Sep 17 00:00:00 2001 From: Stephen Searles Date: Sun, 2 Jul 2017 23:30:07 -0700 Subject: [PATCH] a little more flexibility with scaling images by url --- media.go | 45 +++++++++++++++++++++++++++++++++++++++------ templates.go | 1 - 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/media.go b/media.go index ed3437f..31b34af 100644 --- a/media.go +++ b/media.go @@ -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 diff --git a/templates.go b/templates.go index e346ba7..4830fe2 100644 --- a/templates.go +++ b/templates.go @@ -267,7 +267,6 @@ a { deltas.forEach(function(aceDelta) { var cmDelta = aceDeltaToCM(aceDelta) - console.log(cmDelta); var content = "" var to = {