0

所以我有一张图片,我在图片上写了文字和一个颜色框。它有效,但它被添加到右上角的图像中,但我需要它在图像的中心。我尝试更改 x 和 y 变量,但它只移动文本而不是白框。

这是代码

$image_filepath = './kenshin.jpg';
saveImageWithText("Welcome to Eureka!", $color, $image_filepath);

function saveImageWithText($text, $color, $source_file) { 

  $public_file_path = '.';

  // Copy and resample the imag
  list($width, $height) = getimagesize($source_file);
  $image_p = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($source_file);
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height); 

  // Prepare font size and colors
  $text_color = imagecolorallocate($image_p, 0, 0, 0);
  $bg_color = imagecolorallocate($image_p, 255, 255, 255);
  $font = $public_file_path . '/arial.ttf';
  $font_size = 12; 

  // Set the offset x and y for the text position
  $offset_x = 0;
  $offset_y = 20;

  // Get the size of the text area
  $dims = imagettfbbox($font_size, 0, $font, $text);
  $text_width = $dims[4] - $dims[6] + $offset_x;
  $text_height = $dims[3] - $dims[5] + $offset_y;

  // Add text background
  imagefilledrectangle($image_p, 0, 0, $text_width, $text_height, $bg_color);

  // Add text
  imagettftext($image_p, $font_size, 0, $offset_x, $offset_y, $text_color, $font, $text);

  // Save the picture
  imagejpeg($image_p, $public_file_path . '/output.jpg', 100); 

  // Clear
  imagedestroy($image); 
  imagedestroy($image_p); 
};

这是输出

在此处输入图像描述

4

1 回答 1

0

尝试这个。它会帮助你……</p>

  <?php
    $img = imagecreatefromjpeg("girl-hugging-the-globe.jpg"); // image.jpg is the image on which we are going to write text ,you can replace this iamge name with your
    if(!$img) die("Unabe to load image");
    $red = imagecolorallocate($img, 255, 0, 0);
    $green = imagecolorallocate($img, 0, 255, 0);
    $width = 600;// it will store width of image 
    $height = 100; //it will store height of image
    $fontsize = 6; // size of font
    $text = "Block Prints Online"; // Define the text
    $pos = ( $width - imagefontwidth($fontsize)*STRLEN($text) );// calculate the left position of the text:
    imagestring($img, $fontsize, 200, 150, $text, $red);
    header('Content-type: image/jpeg');
    imagejpeg($img);//it will output a jpeg image
    imagedestroy($img);//it will destroy $img*/
    ?>
于 2013-03-30T08:13:33.863 回答