I am resizing my images and want to get the file size e.g. 36kb of the resized images.
Is this possible with Hugo?
Generally, I would like to be able to get the file size of any page resource so I can put the file size next to the download link of a pdf. This helps people visiting the site on a slow internet connection decide whether they want to download a pdf or view a larger image.
You could maybe adapt this: Local file templates | Hugo to suit. I don’t think Page Resources have the size information readily available, though I’m happy to be corrected.
There is a os.Stat template func that can be used to get size (and lastmod) of files in your Hugo project … but you need to know the filename, which I don’t think you do for all resources … We should fix that …
An slightly ineffective way (as it reads the files into memory) would be:
Thanks for your replies. I got both of them to work.
Option 1
resize the image
{{ $resized := $imageResource.Resize "960x" }}
get the file name from the path
{{ $name := replace $sized.RelPermalink "/uploads/" "" }}
get all the files in the image directory
{{ $theFiles := readDir "/public/uploads" }}
Iterate through them and get the size of the correct file
{{ range $theFiles }}
{{ if eq .Name $name}}
print the size
{{ div .Size 1000 }}Kb
{{ end }}
{{ end }}
Option 2
{{ $sized := $imageResource.Resize .size }}
{{ $sizeInBytes := len $sized.Content }}
print the size
{{ div $sizeInBytes 1000 }}kB
After further experimenting Option 2 is the only one that works consistently on my local machine and in production deployment. @bep said to me in an email