in Ruby on Rails

Adding Borders to Images with RMagick

So I found this awesome gem called RMagick for image manipulation in Ruby on Rails. Railscast has an excellent tutorial on creating thumbnails of uploaded images and getting set up with RMagic. However I wanted to do more than just create a thumbnail of my images. I wanted to easily add a black border to all of the images, much like with Instagram.

If you view the RMagick documentation you will see that there is a function to easily do this called img.border. However, I had a hard time figuring out the implementation of it. You aren’t able to just call this function like the :resize_to_fit function in the Railscast Tutorial. I discovered that you have to write your own function for this inside your /app/uploaders/image_uploader.rb file. This is what I wrote to make this work.

Then where I want to display the image I call :border1 just like you call :thumb when you want to display the thumbnail.

For example:

It wasn’t exactly clear to me how I was suppose to get this to work until I saw this Stackover post and realized I needed to write my own function to make this happen. Hopefully anyone else having this problem can use this to fix their code. I haven’t tested any of the dozens of other RMagick functions, but I imagine this is how it is done for the others as well. Let me know if this helps you sometime.

Here is the result of before and after adding a border (and resizing the image)

Adding Border Using RMagick

Write a Comment