2013-03-30 29 views
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); 
}; 

这里是输出

enter image description here

+0

相同的基本想法http://stackoverflow.com/questions/12310464/centering-image-on-uploaded-image-in-php – jeremy

+0

脚本,我给你能够改变位置文字 –

+0

@mohammad mohsenipur如何更改您的示例文本的背景颜色? –

回答

0

试试这个。它会帮助你...

<?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*/ 
    ?> 
+0

你可以用这张图片测试它吗,因为它只显示没有背景色的红色文字http://i49.tinypic.com/2ufptfn.jpg –