5

あなたが素晴らしいことを願っています。

私はまだphpの初心者なので、読んだ後、ここでいくつかの投稿をチェックしているときに、PHP GDを使用してimagecreatefrompng()関数を使用して画像にテキストを配置できました。ユーザーはフォームに来て、彼らの名前を入力することができ、名前は画像の上に書かれます。残念ながら、テキストの中央を水平に揃えることができませんでした。imagettfbboxで可能な限りの方法を試しました(私の方法は明らかに間違っているに違いありません)が、すべての試みに失敗しました、弦の中心を水平に揃えるために少し手伝ってくれませんか?また、一種の代替の大きなフォントを使用しているため、入力した名前が長い場合はサイズを小さくする必要があるため、この方法では画像の制限を超えず、中央に留まります。

<?php
 $nombre=$_POST['nombre'];
  //Set the Content Type
  header('Content-type: image/jpeg');

  // Create Image From Existing File
  $jpg_image = imagecreatefromjpeg('fabian.jpg');

  // Allocate A Color For The Text
  $white = imagecolorallocate($jpg_image, 255, 255, 255);

  // Set Path to Font File
  $font_path = 'fabian.TTF';

  // Set Text to Be Printed On Image , I set it to uppercase
  $text =strtoupper($nombre);

  // Print Text On Image
  imagettftext($jpg_image, 75, 0, 50, 400, $white, $font_path, $text);



  // Send Image to Browser
  imagepng($jpg_image);

  // Clear Memory
  imagedestroy($jpg_image);

  ?>

ユーザーに右クリックして画像を保存してほしくないので、後で送信ボタンをクリックして画像を保存しようとして頭を悩ませます。

ありがとう!

4

2 に答える 2

17

両方を関連付けるには、画像の幅とテキストの幅が必要です。

// get image dimensions
list($img_width, $img_height,,) = getimagesize("fabian.jpg");

// find font-size for $txt_width = 80% of $img_width...
$font_size = 1; 
$txt_max_width = intval(0.8 * $img_width);    

do {        
    $font_size++;
    $p = imagettfbbox($font_size, 0, $font_path, $text);
    $txt_width = $p[2] - $p[0];
    // $txt_height=$p[1]-$p[7]; // just in case you need it
} while ($txt_width <= $txt_max_width);

// now center the text
$y = $img_height * 0.9; // baseline of text at 90% of $img_height
$x = ($img_width - $txt_width) / 2;

imagettftext($jpg_image, $font_size, 0, $x, $y, $white, $font_path, $text);
于 2013-04-13T01:14:48.880 に答える