Skip to content

Commit

Permalink
Image attachments: use full-resolution file if available (#87)
Browse files Browse the repository at this point in the history
* Image attachments: use full-resolution file if available

Images embedded in posts/pages may sometimes use downscaled image thumbnails or thumbnails sizes that don't exist anymore, patterned like `some-file-1920x1080.jpg`. We try to find the full-resolution image if any, like `some-file.jpg`, then fall-back to whatever URL was given in content if this failed.

This assumes Hugo image partials will handle resizing to theme width and responsive image sizes internally (see https://discourse.gohugo.io/t/hugo-image-processing-and-responsive-images/43110/4).

* Update output file path too if full-res image was found

* Add log lines, refine media retrieving logic

* Fix Go formatting
  • Loading branch information
aurelienpierre authored Dec 4, 2024
1 parent 6209057 commit 9e1fe1e
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/wp2hugo/internal/hugogenerator/hugo_gen_setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path"
"regexp"
"runtime"
"strings"
"time"
Expand Down Expand Up @@ -37,6 +38,9 @@ placeholder: "placeholder text in search input box"
---
`

// Find image media thumbnails resized by WP, like `some-file-1920x1080.jpg`
var _resizedMedia = regexp.MustCompile(`(.*)-\d+x\d+\.(jpg|jpeg|png|webp|gif)`)

type Generator struct {
fontName string
imageURLProvider hugopage.ImageURLProvider
Expand Down Expand Up @@ -478,7 +482,31 @@ func (g Generator) downloadPageMedia(outputMediaDirPath string, p *hugopage.Page
if !strings.HasPrefix(link, "http") {
link = g.wpInfo.Link() + link
}
media, err := g.mediaProvider.GetReader(link)

// Try full-res images first.
// It is assumed here that Hugo will handle responsive sizes and such internally.
// see https://discourse.gohugo.io/t/hugo-image-processing-and-responsive-images/43110/4
fullResLink := _resizedMedia.ReplaceAllString(link, "$1.$2")
media, err := g.mediaProvider.GetReader(fullResLink)

if err != nil {
// If full-res image not found, try again with resized one.
if strings.Compare(fullResLink, link) != 0 {
log.Info().
Str("fullResLink", fullResLink).
Str("link", link).
Msg("full-resolution image file not found, falling back to resized thumbnail")
media, err = g.mediaProvider.GetReader(link)
} // else fullResLink == link, so no need to retry
} else {
// If full-res image found, update target file path too
outputFilePath = _resizedMedia.ReplaceAllString(outputFilePath, "$1.$2")
log.Info().
Str("fullResLink", fullResLink).
Str("link", link).
Msg("resized thumbnail was replaced by full-resolution image")
}

if err != nil {
if g.continueOnMediaDownloadFailure {
log.Error().
Expand Down

0 comments on commit 9e1fe1e

Please sign in to comment.