douhuangjie4503 2014-02-18 23:06
浏览 71
已采纳

php - 在多行上转换单行字符串,然后插入图像

I'm programming a script that inserts a text on an image, it works but not entirely, ie if a user adds a line break in the textarea is fine, but if all the text is on one line looks bad . This is my code

$str="this is a string inserted by an user";
$img_width= 500;
$img_height= 500;
$font_size = 1; 
$txt_max_width = intval(0.6 * $img_width);
do {
    $font_size++;
    $p = imagettfbbox($font_size,0,$font,$str);
    $txt_width=$p[2]-$p[0];
    } while ($txt_width <= $txt_max_width);
    $y = $img_height * 0.4;
$x = ($img_width - $txt_width) / 2;
$white = imagecolorallocate($img, 255, 255, 255);
imagettftext($img, $font_size, 0, $x, $y, $white, $font, $str);
imagepng($img);
imagedestroy($img);

Look at this for understand http://app.xskarx.com

PS: sorry for my bad english

  • 写回答

2条回答 默认 最新

  • dongmou2389 2014-02-19 01:18
    关注

    What you want to do, is to split the string into smaller block or chunks, for that, you have chunk_split in PHP.

    You will use it this way:

    // initialize variables
    $final_string = false;
    $size_of_the_chunk = 20;
    $str = "_this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string_";
    $length_of_string = strlen( $str );
    
    // work only if necessary
    if ( $length_of_string > $size_of_the_chunk ) {
        $final_string = chunk_split( $str, $size_of_the_chunk );
    } else {
        $final_string = $str;
    }
    

    The main problem you may have, is that the string will get split on random places, at least random from the perspective of the user, and so, the fragments may not make much sense. Try to improve the user interface by informing that they should use line breaks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题