website logo
Auteur
avatar
Visiteur

Forum » » Le coin des codeurs » » [Résolu] - Bug du captcha en chinois


Posté : 21 juil. 2026 à 19:02 icone du post

Mets les deux polices dans le dossier fonts/ et teste.
[code php]
<?php

Mets les deux polices dans le dossier fonts/ et teste.

header('!content-type:! image/png');

if ($_GET['page'] == 'chinois') {
    $mot = "四 + 3 = "; // texte chinois codé en dur pour le test
    $fontsDir = 'fonts/';

    $fontFile = preg_match('/[\x{4e00}-\x{9fff}]/u', $mot)
        ? $fontsDir . 'wqy-zenhei.ttc'
        : $fontsDir . 'DejaVuSans.ttf';

    $fontSize = 16;
    $angle = 0;
    $bbox = imagettfbbox($fontSize, $angle, $fontFile, $mot);
    $width  = abs($bbox[2] - $bbox[0]) + 8;
    $height = abs($bbox[1] - $bbox[7]) + 8;

    $img = imagecreatetruecolor($width, $height);
    $blanc = imagecolorallocate($img, 255, 255, 255);
    $noir  = imagecolorallocate($img, 0, 0, 0);
    imagefill($img, 0, 0, $blanc);
    imagecolortransparent($img, $blanc);

    $x = -$bbox[0] + 4;
    $y = -$bbox[7] + 4;
    imagettftext($img, $fontSize, $angle, $x, $y, $noir, $fontFile, $mot);

    imagepng($img);
    imagedestroy($img); // depuis PHP 8.0, imagedestroy() n'a plus aucun effet — depuis PHP 8.0, l'extension GD utilise des objets au lieu de ressources, et les objets ne peuvent pas être fermés explicitement. Et cette fonction a été officiellement dépréciée à partir de PHP 8.5, ce qui déclenche maintenant un warning si tu es sur PHP 8.5+
    if (PHP_VERSION_ID < 80000) {
        imagedestroy($img);
    }
} else {
    $mot = "四 + 3 = "; // même texte chinois codé en dur, pour comparaison directe

    $font = 16;
    $width = imagefontwidth($font) * strlen($mot);
    $height = imagefontheight($font);

    $img = imagecreate($width + 4, $height + 4);
    $blanc = imagecolorallocate($img, 255, 255, 255);
    $noir  = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $blanc);

    imagestring($img, $font, 1, 1, $mot, $noir);

    imagepng($img);
    if (PHP_VERSION_ID < 80000) {
        imagedestroy($img);
    }
}
[/code]
Normalement, après ça, ton captcha chinois devrait être ok et opérationnel.

Cet article provient de NPDS
https://www.npds.org/viewtopic.php?topic=27112&forum=5