# Ruby/GD2: generate image that strictly fits a text

**URL:** <https://www.ruby-forum.com/t/ruby-gd2-generate-image-that-strictly-fits-a-text/140834>\
**Category:** Ruby\
**Created:** [June 19, 2008, 2:09am UTC](https://www.ruby-forum.com/t/ruby-gd2-generate-image-that-strictly-fits-a-text/140834 "2008-06-19T02:09:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jonathan2000](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/fbc32d/32.png) [@jonathan2000](https://www.ruby-forum.com/u/jonathan2000)\
**Post date:** [June 19, 2008, 2:09am UTC](https://www.ruby-forum.com/t/ruby-gd2-generate-image-that-strictly-fits-a-text/140834/1 "2008-06-19T02:09:18Z")

</div>

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!
