Home > Article > Backend Development > How to solve the problem of Chinese garbled characters when adding digital watermark to pictures with PHP_PHP Tutorial
$textcolor = imagecolorallocate($img, 255, 0, 0); //Set the watermark font color
$font = 'c:/windows/fonts/simhei.ttf'; //Define font
$text = iconv("GB2312", "UTF-8", $waterImageUrl); //Convert Chinese text to UTF8
Imagettftext($img, 20, 10, 50, 40, $textcolor, $font, $text);//Write text into the image
$this->outputImage($img, $this->getExtendsName($imageUrl), $imageUrl);
imagedestroy($img);///Destroy the image
In many cases, the problem is solved like this, but don’t forget, there are special cases, that is, you set the php page encoding, such as: header( "Content-Type: text/html; charset =UTF-8 ");
, Well, at this time, if you still use this method, it will be dead, and it will be garbled. Why, because it is already UTF-8, why are you converting it? It's weird. At this time, you can remove the third line and directly change $text in the imagettftext method to $waterImageUrl. Of course, there are more special cases, that is, the page you pass the value to is in another encoding. Instead of UTF-8, I guess there will be another article. Therefore, I advise friends who are learning PHP to ensure that the encoding of each page in your website is consistent. In this way, the problem will be solved much more easily.
I’d better post the code, I’m afraid some people don’t know it, www.2cto.com
$textcolor = imagecolorallocate($img, 255, 0, 0); //Set the watermark font color
$font = 'c:/windows/fonts/simhei.ttf'; //Define font
//$text = iconv("UTF-8", "UTF-8", $waterImageUrl); //Convert Chinese text to UTF8
//Actually, you can see that there is no need to convert here, because I have set the encoding to UTF-8 in the previous index.php file, if
//Write as //$text = iconv("GB2312", "UTF-8", $waterImageUrl); Instead, garbled characters will appear
$text = $waterImageUrl;
Imagettftext($img, 20, 10, 50, 40, $textcolor, $font, $text);//Write text into the image
$this->outputImage($img, $this->getExtendsName($imageUrl), $imageUrl);
imagedestroy($img);///Destroy the image