Page 1 of 1

[Resolved] How to center a text in an image

Posted: 2012-03-30T10:46:26-07:00
by kernel34
Hi,
I would like to copy a circle in a image and then center a number inside that circle.
I tried but it doesn't work, here is my code.
convert -version Ubuntu 32
Version: ImageMagick 6.6.0-4 2011-06-15 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2010 ImageMagick Studio LLC
Features: OpenMP

Code: Select all

<?php 
$image = new Imagick('./blank.png');
$circle = new Imagick('./circle.png');

$circle_geo = $circle->getImageGeometry();

$number = 11;
$number_font = './MyriadPro-Bold.otf';

$circle_pos_x = 150;
$circle_pos_y = 150;
// copy the circle
$image->compositeImage($circle, $circle->getImageCompose(), $circle_pos_x, $circle_pos_y);

$draw = new ImagickDraw();
$draw->setFillColor('white');
$draw->setFont($number_font);
$draw->setFontSize(20);

$metrics = $circle->queryfontmetrics($draw, $number);

$x = $circle_pos_x + ($circle_geo['width']/2) - ($metrics['textWidth']/2);
$y = $circle_pos_y + ($circle_geo['height']/2) + ($metrics['textHeight']/2);	
    
$image->annotateImage($draw, $x, $y, 0, $number);
$image->writeImage("./test.png");
?>
Image
if you wanna test here is the link of the circle image : http://i39.tinypic.com/jjy6pk.png

thanks

Re: How to center a text in an image

Posted: 2012-03-31T09:57:19-07:00
by kernel34
Finally i used set gravity to center the text.
Here is the code :

Code: Select all

<?php 
$image = new Imagick('./blank.png');
$circle = new Imagick('./circle.png');

$circle_geo = $circle->getImageGeometry();

$number = 11;
$number_font = './MyriadPro-Bold.otf';

$circle_pos_x = 150;
$circle_pos_y = 150;

$image->compositeImage($circle, $circle->getImageCompose(), $circle_pos_x, $circle_pos_y);

$draw = new ImagickDraw();
$draw->setFillColor('white');
$draw->setFont($number_font);
$draw->setFontSize(20);
$draw->setGravity(imagick::GRAVITY_CENTER);

$metrics = $circle->queryfontmetrics($draw, $number);

$x = $circle_pos_x + ($circle_geo['width']/2) - ($metrics['textWidth']/2);
$y = $circle_pos_y + ($circle_geo['height']/2) + ($metrics['textHeight']/2);	
    
$circle->annotateImage($draw, 0, 0, 0, $number);
$image->compositeImage($circle, $circle->getImageCompose(), $circle_pos_x, $circle_pos_y);
$image->writeImage("./test.png");
?>
Thanks to grepper for his help in #imagemagick on Freenode

Re: [Resolved] How to center a text in an image

Posted: 2012-04-01T23:15:05-07:00
by anthony
Unfortunatally both placement and justification at that position are both gravity controlled. :-(

Separating the two (gravity for placement and justification override) is something I want to add to IMv7