PHP 5: how to write utf-8 binary data - image - to

2019-08-04 09:07发布

问题:

I have a Ubuntu server and PHP5, and the PHP script files, and all output are in UTF-8. I'm trying to send an image to the output stream, but just garbled chinese characters shows up in the output:

$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
header('Content-type: image/jpeg');
imagejpeg($im);
imagedestroy($im);

any suggestions?

回答1:

Your code works perfectly fine on my machine :

<?php
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
header('Content-type: image/jpeg');
imagejpeg($im);
imagedestroy($im);

die;
?>

Are you sure you are not outputing anything before or after that code ? Even any kind of whitespace would be a source of troubles.

Or maybe your script is doing something else somewhere ?


If it still doesn't work, maybe trying with imagettftext, to use a "better" / more complete font than the ones used by imagestring might help ?

Using something like this, for instance :

$font = '/usr/share/fonts/truetype/msttcorefonts/arial.ttf';
imagettftext($im, 20, 0, 10, 20, $text_color, $font, 'A Simple éléphant String');


BTW, did you try without those line :

header('Content-type: image/jpeg');
imagejpeg($im);
imagedestroy($im);

If there is an error/warning/notice, removing those lines might help you seeing those.


And, as a sidenote : using JPEG for images that contain some text generally doesn't give great results, as JPEG is a destructive compression mechanism. Using PNG, in that kind of situation, might get you better results ;-)



回答2:

Try removing the UTF-8 byte order mark, because it gets prepended to the contents of your JPEG image, rendering it invalid.



标签: php file utf-8