When our staff build the frontend of a site is always necessary redefine the thumbs of an Image.
99% of our customers change the size or the final layout is a little different
It's true our attachment table can define thumbs and we can reprocess them like showed in this article
But if don't want every time add a new line in our code and reprocess all of them?
If the image did't reside on our server?
image_tag("/path/to/my/image.png", :size => "180#")
image_tag("http://www.remote.com/image.png", :size => "180x180!")
Create on the fly (and once time) a new image in our public folder
For all this reasons I create a small but usefull helper
The code is pretty documented
require 'open-uri' def image_tag(source, options = {}) options.symbolize_keys! # We set here the upload path upload_path = "uploads/thumbs" # Now we can create a thumb on the fly if options[:size] || options[:width] || options[:height] begin geometry = options[:size] geometry ||= [options[:width], options[:height]].join("x") filename = File.basename(source) # Checking if we have just process them # We don't want to do the same job two times if File.exist?("#{Rails.root}/public/#{upload_path}/#{geometry}_#{filename}") options[:src] = "/#{upload_path}/#{geometry}_#{filename}" else # We need to create the thumb FileUtils.mkdir("#{Rails.root}/tmp") unless File.exist?("#{Rails.root}/tmp") # We create a temp file of the original file # Notice that we can download them from an url! # So this Image can reside anywhere on the web if source =~ /#{URI.regexp}/ tmp = File.new("#{Rails.root}/tmp/#{filename}", "w") tmp.write open(source).read tmp.close else # If the image is local tmp = File.open(File.join("#{Rails.root}/public", path_to_image(source).gsub(/\?+\d*/, ""))) end # Now we generate a thumb with our Thumbnail Processor (based on Paperclip) thumb = Lipsiadmin::Attachment::Thumbnail.new(tmp, :geometry => geometry).make # We check if our dir exists unless File.exist?("#{Rails.root}/public/#{upload_path}") FileUtils.mkdir("#{Rails.root}/public/#{upload_path}") end # Now we put the image in our public path new_file_path = "#{Rails.root}/public/#{upload_path}/#{geometry}_#{filename}" File.open(new_file_path, "w") do |f| f.write thumb.read end # Finally we return the new image path options[:src] = "/#{upload_path}/#{geometry}_#{filename}" end rescue Exception => e options[:src] = path_to_image(source) ensure File.delete(tmp.path) if tmp && source =~ /#{URI.regexp}/ File.delete(thumb.path) if thumb end end options[:src] ||= path_to_image(source) options[:alt] ||= File.basename(options[:src], '.*'). split('.').first.to_s.capitalize if mouseover = options.delete(:mouseover) options[:onmouseover] = "this.src='#{image_path(mouseover)}'" options[:onmouseout] = "this.src='#{image_path(options[:src])}'" end tag("img", options) end
