Need to handle image uploads in your Rails app? Give DynamicImage a try.
Rather than creating a pre-defined set of images when a file is uploaded, DynamicImage stores the original file and generates images on demand. It handles cropping, resizing, format and colorspace conversion.
Supported formats at the moment are JPEG, PNG, GIF, BMP and TIFF. The latter will automatically be converted to JPG. CMYK images will be converted to RGB, and RGB images will be converted to the sRGB colorspace for consistent appearance in all browsers.
All URLs are signed with a HMAC to protect against denial of service and enumeration attacks.
- Rails 5
- Ruby 2.4+
- ImageMagick command line tools
Add the gem to your Gemfile and run
gem "dynamic_image", "~> 2.0.0"
dis:install generator to set up your storage.
bin/rails generate dis:install
You can edit the generated initializer to configure your storage, by default it
will store files in
db/dis. See the
Dis documentation for more
Creating your resource
dynamic_image:resource generator to create your resource.
bin/rails generate dynamic_image:resource image
This will create an
Image model and a controller, along with a migration and
the necessary routes.
Note that in this case, the route with collide with any static images stored
public/images. You can customize the path if you want in the route
image_resources :images, path: "dynamic_images/:digest(/:size)"
Storing an image
To save an image, simply assign the file attribute to your uploaded file.
image_params = params.require(:image).permit(:file) Image.create(image_params)
Rendering images in your views
You should use the provided helpers for displaying images, this will ensure that the generated URLs are properly signed and timestamped.
To display the image at it's original size, use
<%= dynamic_image_tag(image) %>
To resize it, specify a max size. This will scale the image down to fit, but no cropping will occur.
<%= dynamic_image_tag(image, size: "400x400") %>
crop: true will crop the image to the exact size.
<%= dynamic_image_tag(image, size: "400x400", crop: true) %>
Omitting either dimension will render the image at an exact width or height.
<%= dynamic_image_tag(image, size: "400x") %>
dynamic_image_url act pretty much like regular URL
<%= link_to "See image", dynamic_image_path(image) %>
Generating images on the fly is expensive. This is less of a problem in development mode, as DynamicImage respects the If-Modified-Since header. In production, you should absolutely cache the results.
DynamicImage doesn't do any caching on it's own, but it is designed to play well with others. Here's a few options:
It's perfectly safe to cache images indefinitely. The URL is timestamped, and will change if the object changes.
Copyright 2006-2016 Inge Jørgensen
DynamicImage is released under the MIT License.