Created
November 1, 2008 09:55
-
-
Save dsturnbull/21495 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# formats - array of MediaFormat objects | |
# :width - desired width | |
# :height - desired height | |
# :fuzz - number of pixels it's ok to be off by | |
# :constrain - scale image client-side to specified :width and :height, using image best matching specified :width and :height | |
# :include_cropped - include cropped images | |
def image_helper(formats, options={}) | |
options[:constrain] = true unless options[:constrain].blank? | |
options[:fuzz] ||= 0 | |
options[:include_cropped] ||= false | |
desired_w = options[:width] + options[:fuzz] | |
desired_h = options[:height] + options[:fuzz] | |
closest = 10000 | |
format = formats.first | |
#LOG.debug "looking for #{options[:width]}/#{options[:height]}" | |
# choose the format that is closest to the desired size, as long as it's not larger (+ fuzz) | |
formats.each do |f| | |
next if !options[:include_cropped] && ImageFormat::FORMATS[f.name][:crop] rescue false | |
next if (f.original and f.content_type != 'image/jpeg') | |
#LOG.debug "#{f.name}: #{f.width}/#{f.height}" | |
[desired_w - f.width, desired_h - f.height].each do |dist| | |
#LOG.debug "not considering #{f.name} because #{dist} < 0" unless dist >= 0 | |
# negative means too big. | |
break if dist < 0 | |
#LOG.debug "is #{dist} < #{closest}?" | |
if dist < closest | |
closest = dist | |
format = f | |
#LOG.debug "yes, using #{format.name} (#{format.width}/#{format.height}). closest is now #{closest}" | |
else | |
#LOG.debug "no." | |
end | |
end | |
end | |
if options[:constrain] | |
w, h = scale_image_params(format.width, format.height, options[:width], options[:height]) | |
else | |
w = format.width | |
h = format.height | |
end | |
#LOG.debug "fmt: #{format.width}/#{format.height}, wanting #{options[:width]}/#{options[:height]}, scaled to #{w}/#{h}" | |
image_tag(format.uri, :width => w, :height => h) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment