PHP5 - I want to write a Hindi text on image

2019-07-06 05:43发布

I want to write a Hindi text(say "पुलिसवाला आमिर खान" ) on an image using PHP5.

I am using

$im = @imagecreate(210, 50);
$background_color = imagecolorallocate($im, 255, 255, 255); 
$text_color = imagecolorallocate($im, 0, 0, 0); 
imagestring($im, 7, 15, 15, utf8_encode("पुलिसवाला आमिर खान..."), $text_color);
ImagePNG($im, 'a.png'); 
imagedestroy($im);

3条回答
Juvenile、少年°
2楼-- · 2019-07-06 06:12

Use function imagettftext and hindi font.
Path to font should be absolute (use realpath or just write absolute path).

查看更多
Bombasti
3楼-- · 2019-07-06 06:12

You will definitely need a solution that works with a Truetype font, imagestring() won't cut it.

  1. Get hold of a TTF font containing Hindi characters tht you can use

  2. get rid of the utf8_encode(), just make sure the file is UTF8 encoded

  3. use imagefttext() instead of imagestring()

查看更多
虎瘦雄心在
4楼-- · 2019-07-06 06:18

You can use imagettftext() to write text onto images as long as your host supports GD2 and FreeType (as most servers do). You can find its detailed syntax and comments here:

http://php.net/manual/en/function.imagettftext.php

Find a font (*.ttf or *.otf) that supports Hindi characters. Put the font file in the same directory as your script, and then try this code -- substituting "yourhindifont.ttf" for your own font filename:

    <?php

    // your string, preferably read from a source elsewhere
    $utf8str = "पुलिसवाला आमिर खान";

    // buffer output in case there are errors
    ob_start();

    // create blank image
    $im = imagecreatetruecolor(400,40);
    $white = imagecolorallocate($im,255,255,255);
    imagefilledrectangle($im,0,0,imagesx($im),imagesy($im),$white);

    // write the text to image
    $font = "yourhindifont.ttf";
    $color = imagecolorallocatealpha($im, 50, 50, 50, 0); // dark gray
    $size = 20;
    $angle = 0;
    $x = 5;
    $y = imagesy($im) - 5;
    imagettftext($im, $size, $angle, $x, $y , $color, $font, $utf8str);

    // display the image, if no errors
    $err = ob_get_clean();
    if( !$err ) {
        header("Content-type: image/png");
        imagepng($im);
    } else {
        header("Content-type: text/html;charset=utf-8");
        echo $err;
    }

    ?>

If you plan to input Hindi directly into your source, be sure to set the document encoding of your source to UTF-8 (without BOM) in your editor beforehand. Otherwise the string will not be stored as expected.

查看更多
登录 后发表回答