| 1 |
// Copyright 2019 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 |
"fmt" |
| 19 |
"image" |
| 20 |
"image/color" |
| 21 |
"image/draw" |
| 22 |
"io" |
| 23 |
"sync" |
| 24 |
|
| 25 |
"github.com/bep/imagemeta" |
| 26 |
"github.com/bep/logg" |
| 27 |
"github.com/gohugoio/hugo/config" |
| 28 |
"github.com/gohugoio/hugo/internal/warpc" |
| 29 |
|
| 30 |
"github.com/gohugoio/hugo/media" |
| 31 |
"github.com/gohugoio/hugo/resources/images/meta" |
| 32 |
|
| 33 |
"github.com/gohugoio/gift" |
| 34 |
|
| 35 |
"github.com/gohugoio/hugo/common/himage" |
| 36 |
"github.com/gohugoio/hugo/common/hugio" |
| 37 |
) |
| 38 |
|
| 39 |
func NewImage(f Format, proc *ImageProcessor, img image.Image, s Spec) *Image { |
| 40 |
if img != nil { |
| 41 |
return &Image{ |
| 42 |
Format: f, |
| 43 |
Proc: proc, |
| 44 |
Spec: s, |
| 45 |
imageConfig: &imageConfig{ |
| 46 |
config: imageConfigFromImage(img), |
| 47 |
configLoaded: true, |
| 48 |
}, |
| 49 |
} |
| 50 |
} |
| 51 |
return &Image{Format: f, Proc: proc, Spec: s, imageConfig: &imageConfig{}} |
| 52 |
} |
| 53 |
|
| 54 |
type Image struct { |
| 55 |
Format Format |
| 56 |
Proc *ImageProcessor |
| 57 |
Spec Spec |
| 58 |
*imageConfig |
| 59 |
} |
| 60 |
|
| 61 |
func (i *Image) EncodeTo(conf ImageConfig, img image.Image, w io.Writer) error { |
| 62 |
return i.Proc.Codec.EncodeTo(conf, w, img) |
| 63 |
} |
| 64 |
|
| 65 |
// Height returns i's height. |
| 66 |
func (i *Image) Height() int { |
| 67 |
i.initConfig() |
| 68 |
return i.config.Height |
| 69 |
} |
| 70 |
|
| 71 |
// Width returns i's width. |
| 72 |
func (i *Image) Width() int { |
| 73 |
i.initConfig() |
| 74 |
return i.config.Width |
| 75 |
} |
| 76 |
|
| 77 |
func (i Image) WithImage(img image.Image) *Image { |
| 78 |
i.Spec = nil |
| 79 |
i.imageConfig = &imageConfig{ |
| 80 |
config: imageConfigFromImage(img), |
| 81 |
configLoaded: true, |
| 82 |
} |
| 83 |
|
| 84 |
return &i |
| 85 |
} |
| 86 |
|
| 87 |
func (i Image) WithSpec(s Spec) *Image { |
| 88 |
i.Spec = s |
| 89 |
i.imageConfig = &imageConfig{} |
| 90 |
return &i |
| 91 |
} |
| 92 |
|
| 93 |
// InitConfig reads the image config from the given reader. |
| 94 |
func (i *Image) InitConfig(r io.Reader) error { |
| 95 |
var err error |
| 96 |
i.configInit.Do(func() { |
| 97 |
i.config, _, err = i.Proc.Codec.DecodeConfig(i.Format, r) |
| 98 |
}) |
| 99 |
return err |
| 100 |
} |
| 101 |
|
| 102 |
func (i *Image) initConfig() { |
| 103 |
var err error |
| 104 |
i.configInit.Do(func() { |
| 105 |
if i.configLoaded { |
| 106 |
return |
| 107 |
} |
| 108 |
|
| 109 |
var f hugio.ReadSeekCloser |
| 110 |
|
| 111 |
f, err = i.Spec.ReadSeekCloser() |
| 112 |
if err != nil { |
| 113 |
return |
| 114 |
} |
| 115 |
defer f.Close() |
| 116 |
|
| 117 |
i.config, _, err = i.Proc.Codec.DecodeConfig(i.Format, f) |
| 118 |
}) |
| 119 |
|
| 120 |
if err != nil { |
| 121 |
panic(fmt.Errorf("failed to load image config: %w", err)) |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
func NewImageProcessor(debugl, warnl logg.LevelLogger, wasmDispatchers *warpc.Dispatchers, cfg *config.ConfigNamespace[ImagingConfig, ImagingConfigInternal]) (*ImageProcessor, error) { |
| 126 |
e := cfg.Config.Imaging.Exif |
| 127 |
exifDecoder, err := meta.NewDecoder( |
| 128 |
meta.WithDateDisabled(e.DisableDate), |
| 129 |
meta.WithLatLongDisabled(e.DisableLatLong), |
| 130 |
meta.ExcludeFields(e.ExcludeFields), |
| 131 |
meta.IncludeFields(e.IncludeFields), |
| 132 |
meta.WithWarnLogger(warnl), |
| 133 |
) |
| 134 |
if err != nil { |
| 135 |
return nil, err |
| 136 |
} |
| 137 |
|
| 138 |
m := cfg.Config.Imaging.Meta |
| 139 |
metaDecoder, err := meta.NewDecoder( |
| 140 |
meta.WithFields(m.Fields), |
| 141 |
meta.WithSources(m.Sources...), |
| 142 |
meta.WithWarnLogger(warnl), |
| 143 |
) |
| 144 |
if err != nil { |
| 145 |
return nil, err |
| 146 |
} |
| 147 |
|
| 148 |
webpCodec, err := wasmDispatchers.NewWepCodec() |
| 149 |
if err != nil { |
| 150 |
return nil, err |
| 151 |
} |
| 152 |
if webpCodec == nil { |
| 153 |
return nil, errors.New("webp codec is not available") |
| 154 |
} |
| 155 |
avifCodec, err := wasmDispatchers.NewAvifCodec() |
| 156 |
if err != nil { |
| 157 |
return nil, err |
| 158 |
} |
| 159 |
imageCodec := newCodec(webpCodec, avifCodec, debugl) |
| 160 |
|
| 161 |
return &ImageProcessor{ |
| 162 |
Cfg: cfg, |
| 163 |
exifDecoder: exifDecoder, |
| 164 |
metaDecoder: metaDecoder, |
| 165 |
Codec: imageCodec, |
| 166 |
}, nil |
| 167 |
} |
| 168 |
|
| 169 |
type ImageProcessor struct { |
| 170 |
Cfg *config.ConfigNamespace[ImagingConfig, ImagingConfigInternal] |
| 171 |
exifDecoder *meta.Decoder |
| 172 |
metaDecoder *meta.Decoder |
| 173 |
Codec *Codec |
| 174 |
} |
| 175 |
|
| 176 |
// Filename is only used for logging. |
| 177 |
func (p *ImageProcessor) DecodeExif(filename string, format imagemeta.ImageFormat, r io.Reader) (*meta.ExifInfo, error) { |
| 178 |
return p.exifDecoder.Decode(filename, format, r) |
| 179 |
} |
| 180 |
|
| 181 |
// DecodeMeta decodes metadata from configured sources. |
| 182 |
// Filename is only used for logging. |
| 183 |
func (p *ImageProcessor) DecodeMeta(filename string, format imagemeta.ImageFormat, r io.Reader) (*meta.MetaInfo, error) { |
| 184 |
return p.metaDecoder.DecodeMeta(filename, format, r) |
| 185 |
} |
| 186 |
|
| 187 |
func (p *ImageProcessor) FiltersFromConfig(src image.Image, conf ImageConfig) ([]gift.Filter, error) { |
| 188 |
var filters []gift.Filter |
| 189 |
|
| 190 |
if conf.Rotate != 0 { |
| 191 |
// Apply any rotation before any resize. |
| 192 |
filters = append(filters, gift.Rotate(float32(conf.Rotate), color.Transparent, gift.NearestNeighborInterpolation)) |
| 193 |
} |
| 194 |
|
| 195 |
switch conf.Action { |
| 196 |
case "resize": |
| 197 |
filters = append(filters, gift.Resize(conf.Width, conf.Height, conf.Filter)) |
| 198 |
case "crop": |
| 199 |
if conf.Anchor == SmartCropAnchor { |
| 200 |
bounds, err := p.smartCrop(src, conf.Width, conf.Height, conf.Filter) |
| 201 |
if err != nil { |
| 202 |
return nil, err |
| 203 |
} |
| 204 |
|
| 205 |
// First crop using the bounds returned by smartCrop. |
| 206 |
filters = append(filters, gift.Crop(bounds)) |
| 207 |
// Then center crop the image to get an image the desired size without resizing. |
| 208 |
filters = append(filters, gift.CropToSize(conf.Width, conf.Height, gift.CenterAnchor)) |
| 209 |
|
| 210 |
} else { |
| 211 |
filters = append(filters, gift.CropToSize(conf.Width, conf.Height, conf.Anchor)) |
| 212 |
} |
| 213 |
case "fill": |
| 214 |
if conf.Anchor == SmartCropAnchor { |
| 215 |
bounds, err := p.smartCrop(src, conf.Width, conf.Height, conf.Filter) |
| 216 |
if err != nil { |
| 217 |
return nil, err |
| 218 |
} |
| 219 |
|
| 220 |
// First crop it, then resize it. |
| 221 |
filters = append(filters, gift.Crop(bounds)) |
| 222 |
filters = append(filters, gift.Resize(conf.Width, conf.Height, conf.Filter)) |
| 223 |
|
| 224 |
} else { |
| 225 |
filters = append(filters, gift.ResizeToFill(conf.Width, conf.Height, conf.Filter, conf.Anchor)) |
| 226 |
} |
| 227 |
case "fit": |
| 228 |
filters = append(filters, gift.ResizeToFit(conf.Width, conf.Height, conf.Filter)) |
| 229 |
default: |
| 230 |
|
| 231 |
} |
| 232 |
return filters, nil |
| 233 |
} |
| 234 |
|
| 235 |
func (p *ImageProcessor) ApplyFiltersFromConfig(src image.Image, conf ImageConfig) (image.Image, error) { |
| 236 |
filters, err := p.FiltersFromConfig(src, conf) |
| 237 |
if err != nil { |
| 238 |
return nil, err |
| 239 |
} |
| 240 |
|
| 241 |
if len(filters) == 0 { |
| 242 |
return p.resolveSrc(src, conf.TargetFormat), nil |
| 243 |
} |
| 244 |
|
| 245 |
img, err := p.doFilter(src, conf.TargetFormat, filters...) |
| 246 |
if err != nil { |
| 247 |
return nil, err |
| 248 |
} |
| 249 |
|
| 250 |
return img, nil |
| 251 |
} |
| 252 |
|
| 253 |
func (p *ImageProcessor) Filter(src image.Image, filters ...gift.Filter) (image.Image, error) { |
| 254 |
return p.doFilter(src, 0, filters...) |
| 255 |
} |
| 256 |
|
| 257 |
func (p *ImageProcessor) resolveSrc(src image.Image, targetFormat Format) image.Image { |
| 258 |
if animatedImage, ok := src.(himage.AnimatedImage); ok { |
| 259 |
frames := animatedImage.GetFrames() |
| 260 |
// If e.g. converting an animated GIF to JPEG, we only want the first frame. |
| 261 |
// Preserve the AnimatedImage wrapper for color properties only when there is |
| 262 |
// no actual animation to preserve. Multi-frame animated sources must still be |
| 263 |
// collapsed unless the target format supports animation output. |
| 264 |
shouldExtractFirstFrame := len(frames) < 2 || !targetFormat.SupportsAnimation() |
| 265 |
colorPropsNeedPreserving := himage.HasColorProperties(src) && len(frames) < 2 |
| 266 |
if shouldExtractFirstFrame && !colorPropsNeedPreserving { |
| 267 |
src = frames[0] |
| 268 |
} |
| 269 |
} |
| 270 |
return src |
| 271 |
} |
| 272 |
|
| 273 |
func (p *ImageProcessor) doFilter(src image.Image, targetFormat Format, filters ...gift.Filter) (image.Image, error) { |
| 274 |
filter := gift.New(filters...) |
| 275 |
|
| 276 |
if anim, ok := src.(himage.AnimatedImage); ok { |
| 277 |
frames := anim.GetFrames() |
| 278 |
// Check if we should extract first frame or preserve AnimatedImage wrapper. |
| 279 |
// Preserve AnimatedImage if color properties need to be maintained. |
| 280 |
shouldExtractFirstFrame := len(frames) < 2 || !targetFormat.SupportsAnimation() |
| 281 |
colorPropsNeedPreserving := himage.HasColorProperties(src) && len(frames) < 2 |
| 282 |
if shouldExtractFirstFrame && !colorPropsNeedPreserving { |
| 283 |
src = frames[0] |
| 284 |
} else { |
| 285 |
var bounds image.Rectangle |
| 286 |
firstFrame := frames[0] |
| 287 |
// Preserve bit depth for HDR images. |
| 288 |
var tmp draw.Image |
| 289 |
switch firstFrame.(type) { |
| 290 |
case *image.RGBA64, *image.NRGBA64: |
| 291 |
tmp = image.NewNRGBA64(firstFrame.Bounds()) |
| 292 |
default: |
| 293 |
tmp = image.NewNRGBA(firstFrame.Bounds()) |
| 294 |
} |
| 295 |
for i, frame := range frames { |
| 296 |
gift.New().DrawAt(tmp, frame, frame.Bounds().Min, gift.OverOperator) |
| 297 |
bounds = filter.Bounds(tmp.Bounds()) |
| 298 |
var dst draw.Image |
| 299 |
switch f := frame.(type) { |
| 300 |
case *image.Paletted: |
| 301 |
// Gif. |
| 302 |
dst = image.NewPaletted(bounds, f.Palette) |
| 303 |
case *image.RGBA64: |
| 304 |
dst = image.NewRGBA64(bounds) |
| 305 |
case *image.NRGBA64: |
| 306 |
dst = image.NewNRGBA64(bounds) |
| 307 |
default: |
| 308 |
dst = image.NewNRGBA(bounds) |
| 309 |
} |
| 310 |
filter.Draw(dst, tmp) |
| 311 |
frames[i] = dst |
| 312 |
} |
| 313 |
anim.SetWidthHeight(bounds.Dx(), bounds.Dy()) |
| 314 |
anim.SetFrames(frames) |
| 315 |
|
| 316 |
return anim, nil |
| 317 |
} |
| 318 |
|
| 319 |
} |
| 320 |
|
| 321 |
bounds := filter.Bounds(src.Bounds()) |
| 322 |
|
| 323 |
var dst draw.Image |
| 324 |
switch src.(type) { |
| 325 |
case *image.RGBA: |
| 326 |
dst = image.NewRGBA(bounds) |
| 327 |
case *image.NRGBA: |
| 328 |
dst = image.NewNRGBA(bounds) |
| 329 |
case *image.Gray: |
| 330 |
dst = image.NewGray(bounds) |
| 331 |
case *image.RGBA64: |
| 332 |
dst = image.NewRGBA64(bounds) |
| 333 |
case *image.NRGBA64: |
| 334 |
dst = image.NewNRGBA64(bounds) |
| 335 |
case *image.Gray16: |
| 336 |
dst = image.NewGray16(bounds) |
| 337 |
default: |
| 338 |
dst = image.NewNRGBA(bounds) |
| 339 |
} |
| 340 |
filter.Draw(dst, src) |
| 341 |
|
| 342 |
return dst, nil |
| 343 |
} |
| 344 |
|
| 345 |
func newImageConfig() ImageConfig { |
| 346 |
return ImageConfig{ |
| 347 |
Anchor: -1, // The real values start at 0. |
| 348 |
PreserveSourcePalette: true, |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
type Spec interface { |
| 353 |
// Loads the image source. |
| 354 |
ReadSeekCloser() (hugio.ReadSeekCloser, error) |
| 355 |
} |
| 356 |
|
| 357 |
// Format is an image file format. |
| 358 |
type Format int |
| 359 |
|
| 360 |
const ( |
| 361 |
JPEG Format = iota + 1 |
| 362 |
PNG |
| 363 |
GIF |
| 364 |
TIFF |
| 365 |
BMP |
| 366 |
WEBP |
| 367 |
AVIF |
| 368 |
|
| 369 |
// Below: We have no encoder/decoder for these, but we can provide metadata support for them (including width/height). |
| 370 |
HEIF |
| 371 |
HEIC |
| 372 |
) |
| 373 |
|
| 374 |
// Whether to use imagemeta to decode image config (width/height ). |
| 375 |
func (f Format) UseImageMetaConfigDecoder() bool { |
| 376 |
return f == WEBP || f == AVIF || f == HEIF || f == HEIC |
| 377 |
} |
| 378 |
|
| 379 |
func (f Format) ToImageMetaImageFormatFormat() imagemeta.ImageFormat { |
| 380 |
switch f { |
| 381 |
case JPEG: |
| 382 |
return imagemeta.JPEG |
| 383 |
case PNG: |
| 384 |
return imagemeta.PNG |
| 385 |
case TIFF: |
| 386 |
return imagemeta.TIFF |
| 387 |
case WEBP: |
| 388 |
return imagemeta.WebP |
| 389 |
case AVIF: |
| 390 |
return imagemeta.AVIF |
| 391 |
case HEIF: |
| 392 |
return imagemeta.HEIF |
| 393 |
case HEIC: |
| 394 |
return imagemeta.HEIF |
| 395 |
default: |
| 396 |
return -1 |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
// SupportsTransparency reports whether it supports transparency in any form. |
| 401 |
func (f Format) SupportsTransparency() bool { |
| 402 |
return f != JPEG |
| 403 |
} |
| 404 |
|
| 405 |
// SupportsAnimation reports whether the format supports animation. |
| 406 |
// AVIF supports animation in the spec, but Hugo's AVIF encoder is single-frame |
| 407 |
// only — including AVIF here would make the pipeline preserve frames just to |
| 408 |
// drop them at encode time. |
| 409 |
func (f Format) SupportsAnimation() bool { |
| 410 |
return f == GIF || f == WEBP |
| 411 |
} |
| 412 |
|
| 413 |
// DefaultExtension returns the default file extension of this format, starting with a dot. |
| 414 |
// For example: .jpg for JPEG |
| 415 |
func (f Format) DefaultExtension() string { |
| 416 |
return f.MediaType().FirstSuffix.FullSuffix |
| 417 |
} |
| 418 |
|
| 419 |
// MediaType returns the media type of this image, e.g. image/jpeg for JPEG |
| 420 |
func (f Format) MediaType() media.Type { |
| 421 |
switch f { |
| 422 |
case JPEG: |
| 423 |
return media.Builtin.JPEGType |
| 424 |
case PNG: |
| 425 |
return media.Builtin.PNGType |
| 426 |
case GIF: |
| 427 |
return media.Builtin.GIFType |
| 428 |
case TIFF: |
| 429 |
return media.Builtin.TIFFType |
| 430 |
case BMP: |
| 431 |
return media.Builtin.BMPType |
| 432 |
case WEBP: |
| 433 |
return media.Builtin.WEBPType |
| 434 |
case AVIF: |
| 435 |
return media.Builtin.AVIFType |
| 436 |
case HEIF: |
| 437 |
return media.Builtin.HEIFType |
| 438 |
case HEIC: |
| 439 |
return media.Builtin.HEICType |
| 440 |
default: |
| 441 |
panic(fmt.Sprintf("%d is not a valid image format", f)) |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
func (f Format) String() string { |
| 446 |
switch f { |
| 447 |
case JPEG: |
| 448 |
return "JPEG" |
| 449 |
case PNG: |
| 450 |
return "PNG" |
| 451 |
case GIF: |
| 452 |
return "GIF" |
| 453 |
case TIFF: |
| 454 |
return "TIFF" |
| 455 |
case BMP: |
| 456 |
return "BMP" |
| 457 |
case WEBP: |
| 458 |
return "WEBP" |
| 459 |
case AVIF: |
| 460 |
return "AVIF" |
| 461 |
case HEIF: |
| 462 |
return "HEIF" |
| 463 |
case HEIC: |
| 464 |
return "HEIC" |
| 465 |
default: |
| 466 |
return "Unknown" |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
type imageConfig struct { |
| 471 |
config image.Config |
| 472 |
configInit sync.Once |
| 473 |
configLoaded bool |
| 474 |
} |
| 475 |
|
| 476 |
func imageConfigFromImage(img image.Image) image.Config { |
| 477 |
if cp, ok := img.(himage.ImageConfigProvider); ok { |
| 478 |
return cp.GetImageConfig() |
| 479 |
} |
| 480 |
b := img.Bounds() |
| 481 |
return image.Config{Width: b.Max.X, Height: b.Max.Y} |
| 482 |
} |
| 483 |
|
| 484 |
// UnwrapFilter unwraps the given filter if it is a filter wrapper. |
| 485 |
func UnwrapFilter(in gift.Filter) gift.Filter { |
| 486 |
if f, ok := in.(filter); ok { |
| 487 |
return f.Filter |
| 488 |
} |
| 489 |
return in |
| 490 |
} |
| 491 |
|
| 492 |
// ToFilters converts the given input to a slice of gift.Filter. |
| 493 |
func ToFilters(in any) []gift.Filter { |
| 494 |
switch v := in.(type) { |
| 495 |
case []gift.Filter: |
| 496 |
return v |
| 497 |
case []filter: |
| 498 |
vv := make([]gift.Filter, len(v)) |
| 499 |
for i, f := range v { |
| 500 |
vv[i] = f |
| 501 |
} |
| 502 |
return vv |
| 503 |
case gift.Filter: |
| 504 |
return []gift.Filter{v} |
| 505 |
default: |
| 506 |
panic(fmt.Sprintf("%T is not an image filter", in)) |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
// IsOpaque returns false if the image has alpha channel and there is at least 1 |
| 511 |
// pixel that is not (fully) opaque. |
| 512 |
func IsOpaque(img image.Image) bool { |
| 513 |
if oim, ok := img.(interface { |
| 514 |
Opaque() bool |
| 515 |
}); ok { |
| 516 |
return oim.Opaque() |
| 517 |
} |
| 518 |
|
| 519 |
return false |
| 520 |
} |
| 521 |
|
| 522 |
// ImageSource identifies and decodes an image. |
| 523 |
type ImageSource interface { |
| 524 |
DecodeImage() (image.Image, error) |
| 525 |
Key() string |
| 526 |
} |