From 823f53c861bb49aecc6104e0add39fc3b0729025 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Mon, 26 Aug 2019 19:12:41 +0200 Subject: Add a set of image filters With this you can do variants of this: ``` {{ $img := resources.Get "images/misc/3-jenny.jpg" }} {{ $img := $img.Resize "300x" }} {{ $g1 := $img.Filter images.Grayscale }} {{ $g2 := $img | images.Filter (images.Saturate 30) (images.GaussianBlur 3) }} ``` Fixes #6255 --- tpl/images/images.go | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) (limited to 'tpl') diff --git a/tpl/images/images.go b/tpl/images/images.go index 4cb809df7..b64456876 100644 --- a/tpl/images/images.go +++ b/tpl/images/images.go @@ -1,4 +1,4 @@ -// Copyright 2017 The Hugo Authors. All rights reserved. +// Copyright 2019 The Hugo Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -15,10 +15,16 @@ package images import ( - "errors" "image" "sync" + "github.com/disintegration/gift" + + "github.com/pkg/errors" + + "github.com/gohugoio/hugo/resources/images" + "github.com/gohugoio/hugo/resources/resource" + // Importing image codecs for image.DecodeConfig _ "image/gif" _ "image/jpeg" @@ -34,13 +40,15 @@ import ( // New returns a new instance of the images-namespaced template functions. func New(deps *deps.Deps) *Namespace { return &Namespace{ - cache: map[string]image.Config{}, - deps: deps, + Filters: &images.Filters{}, + cache: map[string]image.Config{}, + deps: deps, } } // Namespace provides template functions for the "images" namespace. type Namespace struct { + *images.Filters cacheMu sync.RWMutex cache map[string]image.Config @@ -85,3 +93,18 @@ func (ns *Namespace) Config(path interface{}) (image.Config, error) { return config, nil } + +func (ns *Namespace) Filter(args ...interface{}) (resource.Image, error) { + if len(args) < 2 { + return nil, errors.New("must provide an image and one or more filters") + } + + img := args[len(args)-1].(resource.Image) + filtersv := args[:len(args)-1] + filters := make([]gift.Filter, len(filtersv)) + for i, f := range filtersv { + filters[i] = f.(gift.Filter) + } + + return img.Filter(filters...) +} -- cgit v1.2.3