Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Last active December 21, 2022 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acro5piano/b9ff7b080214634482cdceda4b71d2f9 to your computer and use it in GitHub Desktop.
Save acro5piano/b9ff7b080214634482cdceda4b71d2f9 to your computer and use it in GitHub Desktop.
Download & Optimize Hugo images hosted on other websites (e.g. GitHub, imgur, or AWS S3)
  • Confirmed works on Cloudflare pages.
    • Depends on Ruby and wget and imagemagick
  • This script uses JPG with quality 85 and interlace -plane (progressive JPEG)
    • Further improvement like WebP may be required
#!/usr/bin/env ruby
IMAGE_REGEX = /(https:\/\/.*\.(?:png|jpg|jpeg))/
`mkdir -p .cache`
Dir.glob('content/post/*.md') do |file|
puts "===> Start: #{file.to_s}"
content = File.open(file).read
content.scan(IMAGE_REGEX) do |image|
url = image[0]
puts "===> Downloading: #{url}"
`wget -nc -P .cache #{url}`
png = url.split('/')[-1]
jpg = png.sub(/(png|jpg|jpeg)$/, 'jpg')
`convert -quality 85 -interlace Plane .cache/#{png} static/#{jpg}`
content = content.sub(url, "/#{jpg}")
end
File.open(file, 'w') do |f|
f.puts content
end
puts "===> End: #{file.to_s}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment