PHP添加孟加拉语文本至图片时字体显示异常,求解决方案
Fixing Bengali Text Rendering in PHP GD
I see the core issue immediately—those unnecessary encoding conversions are mangling your Bengali text. Let's fix this step by step:
The Problem with Your Current Code
The lines below are converting your valid UTF-8 Bengali text to ISO-8859-1, which doesn’t support Bengali characters. This is why your text shows up broken:
$text = mb_convert_encoding($text, 'HTML-ENTITIES',"UTF-8"); $text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
Corrected Code
Here’s the cleaned-up version that preserves your Bengali text and renders it correctly:
mb_internal_encoding('UTF-8'); header('Content-type: image/jpeg'); // Load your base certificate image $our_image = imagecreatefromjpeg('certificates/main.jpg'); // Define text color (black) $black_color = imagecolorallocate($our_image, 0, 0, 0); // Use a valid Bengali font (ensure the path is correct!) $font_path = 'SolaimanLipi_29-05-06.ttf'; // Adjust path to match your font's location // Your Bengali text (keep it in UTF-8) $text = 'সৌরভ দাস'; // Text rendering parameters $font_size = 50; $angle = 0; $left = 1500; $top = 1400; // Render the text to the image $output = imagettftext($our_image, $font_size, $angle, $left, $top, $black_color, $font_path, $text); // Save the final certificate $imgName = "BDCH-Certificate-maper-".$uid.".jpg"; imagejpeg($our_image, 'certificates/'.$imgName); // Clean up memory resources imagedestroy($our_image);
Additional Troubleshooting Steps
If the text still doesn’t render correctly, check these common issues:
- Font Path: Ensure the font file is in the right location relative to your PHP script. Use an absolute path (like
/var/www/html/fonts/SolaimanLipi_29-05-06.ttf) to avoid path confusion. - FreeType Support: Confirm your GD library has FreeType enabled. Run
phpinfo()and look for "FreeType Support" under the GD section—it should say "enabled". - Font Compatibility: Stick to well-tested Bengali fonts like SolaimanLipi, Kalpurush (UTF-8 version), or Nikosh. Avoid ANSI-encoded fonts, as they don’t support full UTF-8 Bengali characters.
- UTF-8 Validation: Verify your input text is valid UTF-8 using
mb_check_encoding($text, 'UTF-8')to rule out corrupted text.
This should resolve the broken text issue. Let me know if you run into any other hurdles!
内容的提问来源于stack exchange,提问作者Sourav Das
相关产品推荐
相关产品推荐

