Ruby/GD2: generate image that strictly fits a text

Discussion in 'Ruby' started by Jonathan Métillon, Jun 19, 2008.

  1. Hi!

    I'm trying to use GD2::Image and GD2::Font::TrueType to get an image to
    fit a text string. I use the bounding_rectangle() method to extract the
    bounding box (bbox).

    My issue is that the image never really fits the text. It adds some
    margins. Maybe I don't resize the image correctly according to the bbox
    data? Here's my code:

    text = 'some text'
    image = Image.import('white.png') #this is 1x1 white image
    image.draw do |pen|
    pen.font = Font::TrueType['Arial_Bold.ttf', 10]
    pen.color = image.palette.resolve Color[0, 0, 0]
    bbox = pen.font.bounding_rectangle(text)
    width = bbox[:lower_right][0].abs + bbox[:upper_left][0].abs
    height = bbox[:lower_right][1].abs + bbox[:upper_left][1].abs
    image.resize! width, height
    pen.move 0, bbox[:upper_right][1].abs
    pen.text text
    end
    image.export('new-image.png')

    Is there something I can do so the image strictly fits the text, with no
    margin?

    Thank you!
    --
    Posted via http://www.ruby-forum.com/.
    Jonathan Métillon, Jun 19, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jbrewer

    PIL FITs image decoder

    jbrewer, Nov 22, 2005, in forum: Python
    Replies:
    8
    Views:
    1,741
    jbrewer
    Nov 23, 2005
  2. Rob Leslie
    Replies:
    7
    Views:
    242
    Lionel Thiry
    Nov 5, 2005
  3. Rob Leslie

    [ANN] Ruby/GD2 1.0

    Rob Leslie, Nov 15, 2005, in forum: Ruby
    Replies:
    5
    Views:
    120
    Tom Copeland
    Nov 15, 2005
  4. Cheshire Cat

    500 errors with GD2 image generation

    Cheshire Cat, Jun 1, 2006, in forum: Ruby
    Replies:
    0
    Views:
    107
    Cheshire Cat
    Jun 1, 2006
  5. yahata hisashi

    Does Ruby/GD2 work on ruby-mswin32?

    yahata hisashi, Sep 15, 2008, in forum: Ruby
    Replies:
    0
    Views:
    122
    yahata hisashi
    Sep 15, 2008
Loading...

Share This Page