MediaFile: fix thumbnail dimension calculation.

Calculate the dimensions of thumbnails ourselves instead of letting
libvips calculate them for us. This way we know the exact size of
thumbnails, so we can set the right width and height for <img> tags. If
we let libvips calculate thumbnail sizes for us, then we can't predict
the exact size of thumbnails, because sometimes libvips rounds numbers
differently than us.
This commit is contained in:
evazion
2021-11-30 04:17:17 -06:00
parent c2e6202da6
commit e5ba6d4afc
5 changed files with 65 additions and 14 deletions

View File

@@ -202,5 +202,18 @@ class MediaFile
}.stringify_keys
end
# Scale `width` and `height` to fit within `max_width` and `max_height`.
def self.scale_dimensions(width, height, max_width, max_height)
max_width ||= Float::INFINITY
max_height ||= Float::INFINITY
if width <= max_width && height <= max_height
[width, height]
else
scale = [max_width.to_f / width.to_f, max_height.to_f / height.to_f].min
[(width * scale).round.to_i, (height * scale).round.to_i]
end
end
memoize :file_ext, :file_size, :md5, :metadata
end

View File

@@ -72,8 +72,9 @@ class MediaFile::Image < MediaFile
MediaFile::Image.new(output_file)
end
def preview(max_width, max_height)
resize(max_width, max_height, size: :down)
def preview(max_width, max_height, **options)
w, h = MediaFile.scale_dimensions(width, height, max_width, max_height)
resize(w, h, size: :force, **options)
end
def crop(max_width, max_height)