imagettftext function in php causing error

114 Views Asked by At

I am trying to generate captcha image using php and this line in my code is causing a problem:

$x = ($captchaWidth - $text_box[4])/2; //49.5
$y = ($captchaHeight - $text_box[5])/2; //9.5
imagettftext(           <-- This part is causing the error
    $captchaImage,
    $captchaFontSize,
    0,
    $x,
    $y,
    $textColor,
    $captchaFont,
    $captcha
); 

The error is

 PHP Deprecated:  Implicit conversion from float 45.5 to int loses precision
 PHP Deprecated:  Implicit conversion from float 9.5 to int loses precision

So temporarily I am using this:

imagettftext(
    $captchaImage,
    $captchaFontSize,
    0,
    10,
    42,
    $textColor,
    $captchaFont,
    $captcha
); 

Any suggestion will be of great help. Thanks in advance.

1

There are 1 best solutions below

0
Foobar On

If you are fine with using 49.5 as 49 and 9.5 as 9, you can prevent the error doing this:

$x = ($captchaWidth - $text_box[4])/2; //49.5
$y = ($captchaHeight - $text_box[5])/2; //9.5
imagettftext(
    $captchaImage,
    $captchaFontSize,
    0,
    (int)$x,
    (int)$y,
    $textColor,
    $captchaFont,
    $captcha
); 

If 49.5 should be 50 and 49.4 should be 49, then use round()

More info about this topic: https://php.watch/versions/8.1/deprecate-implicit-conversion-incompatible-float-string