Crop circular image with dragonfly rails

笑着哭i 提交于 2019-12-04 17:10:23

Perhaps my solution can help others who are looking for a way to generate rounded images with the Dragonfly gem.

I was not able to find a solution readily available, but I managed to piece something together by taking a little bit here and there.

Turns out there is a very easy way to make rounded images with ImageMagick (6.8.9-1) using the vignette option which is explained here.

The following command line will generate an image with transparent background and the image rounded:

convert profile.png -alpha set -background none -thumbnail 50x50^ -vignette 0x0 rounded_profile.png

We can now get rounded images for profile pictures by adding a :rounded processor to the dragonfly.rb initializer as shown below:

require 'dragonfly'

# Configure
Dragonfly.app.configure do
  plugin :imagemagick

  # Fictive secret no worries
  secret "64d123456dafb767892c1d28ca6d123456ea4cc373dac117d6d1123456a29d6e"

  url_format "/media/:job/:name"

  datastore :file,
    root_path: Rails.root.join('public/system/dragonfly', Rails.env),
    server_root: Rails.root.join('public')

  processor :rounded do |content, size|
    content.shell_update ext: 'png' do |old_path, new_path|
      "/usr/local/bin/convert #{old_path} -alpha set -background none -thumbnail #{size}^ -vignette 0x0 #{new_path}"
    end
  end
end

Notice you might have to change the path for your convert command depending on which platform you are running on, I'm on Mac OS and ImageMagick is installed through Homebrew.

Now from any model having an image handled by Dragonfly you can call:

a_model_instance.an_image.rounded('50x50').url

To return a rounded image which is 50px by 50px.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!