Search code examples
ruby-on-railsruby-on-rails-3imagemagickminimagick

Special characters in c.draw "text" with mini_magick (rails)


I am having quite a bit of trouble getting mini_magick to draw text that contains quotes, double quotes, etc. on an image. I have tried various modifications on c.draw to no avail. What is the best way to escape these characters so that c.draw will display them without an error?

error: non-conforming drawing primitive definitionm'`

produced by

 c.draw "text 8,8 'I'm'" 

Including other special character such as é will result in an error as well. I would like to be able to accept text strings from users as input, therefore the need for Unicode compatibility.


Solution

  • Did you see...

    ?

    In any case, the following works for me on the commandline:

    convert \
       -size 500x100 xc:none \
       -box yellow \
       -pointsize 72 \
       -gravity center \
       -draw "text 8,8 '  \'I\'m\'  '" \
       -trim \
       +repage \
        special-chars.png
    

    and produces this:
    Example PNG showing special characters created with ImageMagicks text drawing function

    For more complicated text drawing requirements, you are strongly advised to circumvent all the escaping by writing your drawing commands into a separate *.mvg (Magick Vector Graphic) file. For example with this content in 1.mvg:

     text 8,8 "öäü ß ÄÖÜ é"
    

    and this command:

    convert \
       -size 250x100 xc:none \
       -box yellow \
       -pointsize 72 \
       -gravity center \
       -draw @1.mvg \
       -trim \
       +repage \
        special-chars.png
    

    you'll get
    More special characters via an .mvg file

    Or even, with 2.mvg:

    push graphic-context
     viewbox 0 0 600 100
     push graphic-context
       fill 'orange'
       rectangle 0,0 600,100
     pop graphic-context
     push graphic-context
       fill 'white'
       font Palatino-Roman
       font-size 48
       stroke-width 2
       gravity SouthEast
       text 8,8 "äöü ß ÄÖÜ é"
     pop graphic-context
     push graphic-context
       fill 'green'
       rectangle 10,10 300,90
     pop graphic-context
     push graphic-context
       fill 'red'
       font Palatino-Bold-Italic
       font-size 28
       stroke-width 1
       text 18,40 "€ ¥ © ℉ ậ ḁ å ǎ à ç ë ĵ"
     pop graphic-context
    pop graphic-context
    
    and this command:

    convert 2.mvg 2.png
    

    you can get:
    ...and even more special characters