github.com/shohhei1126/hugo@v0.42.2-0.20180623210752-3d5928889ad7/tpl/images/images.go (about) 1 // Copyright 2017 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package images 15 16 import ( 17 "errors" 18 "image" 19 "sync" 20 21 // Importing image codecs for image.DecodeConfig 22 _ "image/gif" 23 _ "image/jpeg" 24 _ "image/png" 25 26 // Import webp codec 27 _ "golang.org/x/image/webp" 28 29 "github.com/gohugoio/hugo/deps" 30 "github.com/spf13/cast" 31 ) 32 33 // New returns a new instance of the images-namespaced template functions. 34 func New(deps *deps.Deps) *Namespace { 35 return &Namespace{ 36 cache: map[string]image.Config{}, 37 deps: deps, 38 } 39 } 40 41 // Namespace provides template functions for the "images" namespace. 42 type Namespace struct { 43 cacheMu sync.RWMutex 44 cache map[string]image.Config 45 46 deps *deps.Deps 47 } 48 49 // Config returns the image.Config for the specified path relative to the 50 // working directory. 51 func (ns *Namespace) Config(path interface{}) (image.Config, error) { 52 filename, err := cast.ToStringE(path) 53 if err != nil { 54 return image.Config{}, err 55 } 56 57 if filename == "" { 58 return image.Config{}, errors.New("config needs a filename") 59 } 60 61 // Check cache for image config. 62 ns.cacheMu.RLock() 63 config, ok := ns.cache[filename] 64 ns.cacheMu.RUnlock() 65 66 if ok { 67 return config, nil 68 } 69 70 f, err := ns.deps.Fs.WorkingDir.Open(filename) 71 if err != nil { 72 return image.Config{}, err 73 } 74 defer f.Close() 75 76 config, _, err = image.DecodeConfig(f) 77 if err != nil { 78 return config, err 79 } 80 81 ns.cacheMu.Lock() 82 ns.cache[filename] = config 83 ns.cacheMu.Unlock() 84 85 return config, nil 86 }