Search code examples
svgimagemagickautoresize

fitting text into the box


on my website i allow users to create pictures with line of text they specify drawn on the picture

currently i use for that imagemagick convert - i specify svg template and let convert do the rest

here is part of code which is responsible for outputting text in the picture

  <text text-anchor="middle" x="50%%" y="%s"
        font-family="Times New Roman" font-size="55"
        style="fill:rgb(255,255,255);">
    %s
  </text>

my problem is that if user provides very long strings, the text doesn't fit in the image.

i'd like text to be resized automatically to smaller font if it doesn't fit the picture. is it possible to do with svg templates? if not, what could be other solutions


Solution

  • solved by abandoning svg and doing everything with imagemagick convert and mvg template

    here's the simplified script example in case anyone's pursuing something similar

    script is putting an image and a title on the canvas. title is created with separate convert command, saved as temporary file and then put onto the canvas

    #!/bin/sh
    
    TEMPLATE="
    push graphic-context
    viewbox 0 0 600 600 
    affine 1 0 0 1 0.0 0.0
    push graphic-context
    fill 'rgb(0,0,0)'
    rectangle 0,0 600,600
    pop graphic-context
    push graphic-context
    image Over 38,38 338,338 '%s' 
    pop graphic-context
    push graphic-context
    image Over 36,400 529,55 '%s' 
    pop graphic-context
    pop graphic-context
    ";
    
    #1. creating label fitting specified proportions 
    #2. converting mvg template to jpeg image (and trimming it in process) 
    #3. removing temp file with label
    
    convert -size 529x55 -background black -family "Times New Roman" -gravity center -fill white label:"$2" "tmp/$1title.jpg" && printf "$TEMPLATE"  "images/$1.jpg" "tmp/$1title.jpg"  | convert mvg:- -trim +repage -bordercolor black -border 36  "images/$1converted.jpg" && rm "tmp/$1title.jpg"
    
    #script parameters: $1 is image id, $2 is title text