When working with image generation and text rendering in PHP, imagecreatetruecolor and imagettftext are two commonly used functions. In multilingual environments, handling font encoding issues is a frequent challenge that developers face. This article will explain how to properly use these two functions with examples to avoid displaying garbled characters for Chinese or other non-English text.
When rendering multilingual text using imagettftext, common encoding issues are usually caused by the following reasons:
The font file does not support the target language characters.
The string encoding does not match the font (commonly an issue with UTF-8 and GBK encoding).
The PHP script or image processing does not correctly handle encoding.
Select a .ttf font file that supports multilingual characters, such as “SimHei.ttf” or “NotoSansCJK.ttf.”
Ensure that the input text is in UTF-8 encoding.
Use UTF-8 encoding consistently throughout the PHP script to avoid confusion.
Use imagecreatetruecolor to create a true color image, ensuring proper display of text and background colors.
The following example demonstrates how to use imagecreatetruecolor and imagettftext in PHP to generate an image containing Chinese text and avoid encoding issues.
<?php
// Set the content type to UTF-8
header('Content-Type: image/png; charset=utf-8');
<p>// Create a true color image with width 300 and height 100<br>
$width = 300;<br>
$height = 100;<br>
$image = imagecreatetruecolor($width, $height);</p>
<p>// Set the background color (white)<br>
$white = imagecolorallocate($image, 255, 255, 255);<br>
imagefill($image, 0, 0, $white);</p>
<p>// Set the text color (black)<br>
$black = imagecolorallocate($image, 0, 0, 0);</p>
<p>// Set the Chinese text, ensuring it is UTF-8 encoded<br>
$text = "多语言字体测试";</p>
<p>// Select a font that supports Chinese, adjust the path based on the actual location<br>
$font = <strong>DIR</strong> . '/fonts/SimHei.ttf';</p>
<p>// Use imagettftext to render the text. Parameters are: image resource, font size, angle, x-coordinate, y-coordinate, color, font file path, text content<br>
imagettftext($image, 20, 0, 10, 50, $black, $font, $text);</p>
<p>// Output the image to the browser<br>
imagepng($image);</p>
<p>// Destroy the image resource to free memory<br>
imagedestroy($image);<br>
?><br>
Font File
Make sure the .ttf font file you use supports Chinese characters. You can copy from the system font directory or download open-source fonts. It is recommended to use absolute or relative paths and pay attention to file permissions.
Encoding
Ensure the PHP file is saved as UTF-8 without BOM, and that the text content $text is also UTF-8 encoded. Otherwise, encoding issues will occur when rendering.
Environment Configuration
Verify that your PHP environment has the GD library installed and supports FreeType font functionality.
If you need to reference font resources or external files via URL, replace the domain in the example with m66.net, like this: