nulltek
nulltek

Reputation: 3337

Writing text with spaces using mini_magick and ruby

I'm working on a small rails 5.0.0.1 app that generates text on top of images similar to memes. I have the basic code written in the model as such.

class Meme < ApplicationRecord
  require 'mini_magick'
  mount_uploader :attachment, AttachmentUploader

  def process_image(img_id, top_text, bottom_text)
    image = MiniMagick::Image.open(Img.find(img_id).attachment.current_path)
    image.combine_options do |c|
      c.gravity 'Center'
      c.pointsize '22'
      c.draw "text 200,200 #{top_text}"
      c.fill 'white'
      c.draw "text 100,100 #{bottom_text}"
      c.fill 'white'
    end
    self.attachment = image
    self.save
  end
end

When I'm running this from the console and do the following:

 m = Meme.new
 m.process_image(Img.last.id, "Good", "Stuff") 

It generates the image with the text overlaid properly.

Now when I do the same thing and include whitespace in the captions like this:

m = Meme.new
m.process_image(Img.last.id, "This is", "Totally Weird") 

I get an exception raised in the console like so:

mogrify: non-conforming drawing primitive definition `is' @ error/draw.c/DrawImage/3259.
mogrify: non-conforming drawing primitive definition `Weird' @ error/draw.c/DrawImage/3259.
mogrify: non-conforming drawing primitive definition `is' @ error/draw.c/DrawImage/3259.
mogrify: non-conforming drawing primitive definition `Weird' @ error/draw.c/DrawImage/3259. 

I looked at the API docs for mini_magick and did not see anything related to whitespacing. I see tons of links talking about how to get ImageMagick core to inject whitespaces properly but not using the mini_magick wrapper.

Am I missing something or should I be doing some sort of substitution for the whitespace?

Upvotes: 0

Views: 925

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

The spaces matter:

  # on "This is" input is becomes
  #                           ⇓⇓ mini_magick does not expect that
  # c.draw "text 200,200 This is"
  #                    ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓ HERE
  c.draw "text 200,200 #{top_text}"
  c.fill 'white'
  c.draw "text 100,100 #{bottom_text}"

Quote the strings for mini_magick:

  #                    ⇓           ⇓ HERE
  c.draw "text 200,200 '#{top_text}'"
  c.fill 'white'
  c.draw "text 100,100 '#{bottom_text}'"

Upvotes: 5

Related Questions