Current Location: Home> Latest Articles> How to Solve Text Display Corruption in the imagestring Function?

How to Solve Text Display Corruption in the imagestring Function?

gitbox 2025-10-01

<?php
// Start of the content
echo "

How to Solve Text Display Corruption in the imagestring Function?

";

// Main content
echo "

In PHP, the imagestring function is used to draw text on an image. However, in certain cases, when using Chinese or other non-ASCII characters directly, text corruption may occur. This happens because the imagestring function only supports single-byte characters encoded in ISO-8859-1, while Chinese characters are multi-byte characters.

"
;

echo "

Common Solutions

"
;

echo "

    ";
    echo "
  1. Use the mb_convert_encoding function for encoding conversion: Before drawing Chinese characters, convert the string from UTF-8 to GB2312. For example:
  2. "
    ;
    echo "
    <br>
    </span></span><span><span>$text</span></span><span> = 'Chinese Test';<br>
    </span><span><span>$text</span></span><span> = mb_convert_encoding($text, 'GB2312', 'UTF-8');<br>
    imagestring($image, 5, 10, 10, $text, $color);<br>
    
    ";

    echo "

  3. Use the imagettftext function instead of imagestring: imagettftext supports TrueType fonts and can correctly display Chinese characters. For example:
  4. "
    ;
    echo "
    <br>
    $font = 'path/to/your/font.ttf';<br>
    $text = 'Chinese Test';<br>
    imagettftext($image, 20, 0, 10, 50, $color, $font, $text);<br>
    
    "
    ;

    echo "

  5. Ensure the image and browser output encoding match: Before outputting the image, set the appropriate header, for example:
  6. "
    ;
    echo "
    <br>
    header('Content-Type: image/png');<br>
    
    "
    ;

    echo "

"
;

echo "

In conclusion, the key to solving the imagestring Chinese text corruption issue is: imagestring does not support multi-byte characters. Therefore, it is recommended to use imagettftext along with an appropriate font file.

"
;
?>


<?php // Footer content, unrelated to the article echo "This is the footer information, unrelated to the main content.\n"; ?>

This article fully demonstrates:

  1. Separating PHP output from the main content.

  2. The main content details the causes of and solutions to the imagestring Chinese text corruption issue.

  3. Using