If you want to programatically add a text to an image with Ruby, using RMagick is a simple and quick way to get it done. There is nothing new here, and there are a few articles explaining how to do it already. However when I had to get it to work it for a side project, I ran into some minor issues with the code already published, so I figured I’d share what I did myself!
Installing RMagick and ImageMagick
RMagick uses ImageMagick behind the scene, so you’ll need to install it. When I did it I had some issues with the installation steps provided, especially when it came to generating jpg on MacOS. Using this command instead fixed the problems:
brew install imagemagick --build-from-source
Then you can install bundler and setup your
One the file is created, you can run:
gem install bundler bundle install
…and you should be all set.
In the same folder, add your source image
background.jpg and a new Ruby file
image_generation.rb. Now to write the actual code:
To run the script, simply go
ruby image_generation.rb and that should generate a new image,
I tried to keep the example really simple and copy/pastable. If you want to change the text formatting, there are a lot of options available. Just know that in a lot of cases, if you make a mistake, the changes won’t be applied but you will not get any error message. This is especially confusing when you are trying to do some really minor alterations.
You can find the different possibilities in the documentation and play around to get something that looks the way you want.
Since you scrolled this far, you might be interested in some other things I wrote:
- Misuse of update/update! in Ruby on Rails
- Regression Testing For Data
- Expressing Intent Without Comments In Ruby
- The Difference Between to_s & to_str In Ruby
- Understanding Rails' Forgery Protection Strategies
- First Impressions: Rails 5 on Google App Engine
- Automatically Run RSpec on Multiple Projects
- Startup & Tech Book Reviews