使用PHP GD和图像功能合并2个图像

时间:2019-03-04 04:48:40

标签: php php-gd

我正在创建一个插件,其中我使用字体文件来生成文本,然后将其转换为图像,并在两侧附加2条链以使其具有适当的外观。

Nameplate Image

但是问题是,两侧的链条都是按位置给出的,因此显然不会碰到每个字母的文本。

任何不同的解决方案都可以按预期进行。我正在发布当前代码,请让我知道如何解决此问题并将链条固定在起始和结束字母上。

$text  = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
$color  = isset( $_POST['color'] ) ? sanitize_text_field( wp_unslash( $_POST['color'] ) ) : '';
$st yle  = isset( $_POST['style'] ) ? sanitize_text_field( wp_unslash( $_POST['style'] ) ) : '';
$align  = isset( $_POST['align'] ) ? sanitize_text_field( wp_unslash( $_POST['align'] ) ) : '';

ob_start();

// Set the content-type
header('Content-Type: image/png');
$file_id = get_field( "style", $style );
$font = get_attached_file( $file_id['id'] );

// Create the image
$im = imagecreatetruecolor(400, 400);
$color_code = imagecolorallocate($im, 192, 192, 192);

// Create some colors
$grey = imagecolorallocate($im, 128, 128, 128);
$white = imagecolorallocate($im, 255, 255, 255);
imagealphablending($im, false);
$transparency = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparency);
imagesavealpha($im, true);

list($width, $height) = getimagesize($chain_link_l);
$chain_l = imagecreatefrompng($chain_link_l);
$chain_r = imagecreatefrompng($chain_link_r);

$font_size = kp_create_fontsize(60, $font, $text, $align);

// Get Bounding Box Size
$text_box = imagettfbbox($font_size, 0,$font,$text);

// Get your Text Width and Height
$text_width = $text_box[2]-$text_box[0];
$text_height = $text_box[7]-$text_box[1];

// Calculate coordinates of the text
$x = 200 - ($text_width/2);
$y = 250 - ($text_height/2);
$chain_l_x = $x - 80 + 15 ;
$chain_r_x = $x + $text_width - 23 ;

imagecopyresampled($im, $chain_l, $chain_l_x, 50, 0, 0, 100, 200, $width, $height);
imagecopyresampled($im, $chain_r, $chain_r_x, 50, 0, 0, 100, 200, $width, $height);

// Add the text
imagettftext($im, $font_size, 0, $x+2, $y, $grey, $font, $text);
imagettftext($im, $font_size, 0, $x, $y, $color_code, $font, $text);

imagepng($im);
$imagedata['src'] = base64_encode ( ob_get_contents() );
ob_get_clean();

0 个答案:

没有答案