Php align image with text

Aligning php Generated Image dynamic text in center

I tried fixing this by putting the image into the (to make it it’s parent element), but by doing this the position of the element changes (because the reserved space for the image is still preserved in the element). Check out W3 Schools for more info pertaining to inline VS. block level elements.

Aligning php Generated Image dynamic text in center

i want to align the text generated on the image to the center of the image. for the moment, i dont know if it is possible to align it. below is the code.

$im = @imagecreatefromjpeg('poloroid.jpg'); // Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); //imagefilledrectangle($im, 0, 0, 399, 29, $white); // The text to draw //$text = 'John. '; $fbid = $_POST["id"]; $text = $_POST["want"]; $fb_email =$_POST["email"]; $fb_name=$_POST["name"]; $uploads_dir = 'uploaded_files/'; // Replace path by your own font path $font = 'verdana.ttf'; //image file name //$name ="$fbid.png"; $name = $uploads_dir.$fbid.".png"; //this saves the image inside uploaded_files folder // Add some shadow to the text imagettftext($im, 20, 0, 25, 126, $grey, $font, $text); // Add the text imagettftext($im, 20, 0, 25, 125, $black, $font, $text); // Using imagepng() results in clearer text compared with imagejpeg() //imagepng($im); imagepng($im,$name,9); imagedestroy($im); 
$im = @imagecreatefromjpeg('poloroid.jpg'); // Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); //imagefilledrectangle($im, 0, 0, 399, 29, $white); // The text to draw //$text = 'John. '; $fbid = $_POST["id"]; $text = $_POST["want"]; $fb_email =$_POST["email"]; $fb_name=$_POST["name"]; $uploads_dir = 'uploaded_files/'; // Replace path by your own font path $font = 'verdana.ttf'; $font_size = 20; $angle = 45; //image file name //$name ="$fbid.png"; $name = $uploads_dir.$fbid.".png"; //this saves the image inside uploaded_files folder // Get image Width and Height $image_width = imagesx($im); $image_height = imagesy($im); // Get Bounding Box Size $text_box = imagettfbbox($font_size,$angle,$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 = ($image_width/2) - ($text_width/2); $y = ($image_height/2) - ($text_height/2); // Add some shadow to the text imagettftext($im, $font_size, 0, $x, $y+1, $grey, $font, $text); // Add the text imagettftext($im, $font_size, 0, $x, $y, $black, $font, $text); // Using imagepng() results in clearer text compared with imagejpeg() //imagepng($im); imagepng($im,$name,9); imagedestroy($im); 

You can use stil/gd-text class. Disclaimer: I am the author.

setFontSize(20); $textbox->setFontFace('verdana.ttf'); $textbox->setFontColor(new Color(0, 0, 0)); // black $textbox->setTextShadow( new Color(0, 0, 0, 80), // black color, but 60% transparent 0, -1 // shadow shifted 1px to top ); $textbox->setBox( 0, // distance from left edge 0, // distance from top edge imagesx($im), // textbox width, equal to image width imagesy($im) // textbox height, equal to image height ); // now we have to align the text horizontally and vertically inside the textbox // the texbox covers whole image, so text will be centered relatively to it $textbox->setTextAlign('center', 'center'); // it accepts multiline text $textbox->draw($text); $uploads_dir = 'uploaded_files/'; //image file name //$name ="$fbid.png"; $name = $uploads_dir.$fbid.".png"; //this saves the image inside uploaded_files folder imagepng($im, $name, 9); imagedestroy($im); 

I’ve updated your code a little:

function ImageTTFCenter($image, $text, $font, $size, $angle = 45) < $xi = imagesx($image); $yi = imagesy($image); $box = imagettfbbox($size, $angle, $font, $text); $xr = abs(max($box[2], $box[4])); $yr = abs(max($box[5], $box[7])); $x = intval(($xi - $xr) / 2); $y = intval(($yi + $yr) / 2); return array($x, $y); >$im = @imagecreatefromjpeg('poloroid.jpg'); // Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); //imagefilledrectangle($im, 0, 0, 399, 29, $white); // The text to draw //$text = 'John. '; $fbid = $_POST["id"]; $text = $_POST["want"]; $fb_email =$_POST["email"]; $fb_name=$_POST["name"]; $uploads_dir = 'uploaded_files/'; // Replace path by your own font path $font = 'verdana.ttf'; //image file name //$name ="$fbid.png"; $name = $uploads_dir.$fbid.".png"; //this saves the image inside uploaded_files folder list($x, $y) = ImageTTFCenter($im, $text, $font, 20) // Add some shadow to the4 text imagettftext($im, 20, 0, $x, $y+1, $grey, $font, $text); // Add the text imagettftext($im, 20, 0, $x, $y, $black, $font, $text); // Using imagepng() results in clearer text compared with imagejpeg() //imagepng($im); imagepng($im,$name,9); imagedestroy($im); 

The ImageTTFCenter function will find the center coordinates of you image which you will tell imagettftext

Читайте также:  Running javascript on click

Html — Display text on top of an image, You can use the properties position, z-index and margin to achieve an over-impressed text, with something like this: .myText < position: relative; margin: -100px 0 0 50px; z-index: 5; >.myImage < position: relative; z-index: 0; >In Css using Position relative and absolute you can put the text on top of the image.

How can I get my text to be centered on the same line as my image?

I’m trying to line this logo and the text on the same line, but have the logo on the left hand corner of the site, and the text be centered. Here’s what it looks like now and what the CSS and HTML is so far.

What the site looks like now

#title < font-family: sans-serif; text-align: center; color: #E03DA7; vertical-align: top; display: inline; align-content: right; >body < align-content: center; vertical-align: top; margin: 0; width: 100%; height: 100%; >#navbar < font-family: monospace; font-size: 25px; text-align: center >#mainpara < text-align: left; max-width: 300px; max-height: 750px; font-size: 20px; vertical-align: middle; font-family: sans-serif >img

   

You can achieve the desired results with Flexbox

If you contain your img and h1 in a container (say header ), add the following CSS to the header tag

Results can be found here, with your modified code: JSFiddle

Have the text and picture in one div with text-align centered. Then you can center the div itself if you want it to be in the center.

  

Edit: If you want the text to be centered, you have to take another approach:

#header < position: relative; >h1 < line-height: 60px; text-align: center; >#header img < position: absolute; height: 60px; >#navbar

By using position:absolute on the img tag, you ensure that the h1 tag is centered to the full width of the page.

Читайте также:  Google maps javascript libraries

More of an hackish way, you can put the img and h1 into a div with class .header .

Then set the line-height of the div to the height of the image:

You can see the output here.

How to Center an Image Using Text Align: Center, An element is an inline element (display value of inline-block). It can be easily centered by adding the text-align: center; CSS property to the parent element that contains it. To center an image using text-align: center; you must place the inside of a block-level element such as a

Positioning image next to centered text

I’m having some trouble positioning my image next to my h1 . The h1 is centered, and I would like to have my image placed on the right side of it. However, The position of the h1 may not be changed (thus, the image may not affect the position of the h1 ).

Relevant code I have so far:

This code doesn’t work at all; the image appears on the left side of the web page and is not being positioned relative to the h1 as I would like to.

I tried fixing this by putting the image into the h1 (to make it it’s parent element), but by doing this the position of the h1 element changes (because the reserved space for the image is still preserved in the h1 element).

I hope someone can help me. Kind regards, Nick

That’s because you’re using a block level tag with another block level tag.

Check out W3 Schools for more info pertaining to inline VS. block level elements. 🙂

Читайте также:  Сортировка выбором в javascript

And if you want a more direct example using your code, here is a jsFiddle. This has it so the text is centered and the image is next to it, centered as well.

One solution is to give #header position: relative and position: absolute to the img:

You cannot absolutely position elements with position relative. You should use position absolute.

This wont resize very well though. Hope it helps. 🙂

Since you want them right next to eachother.

Wrap the header text in a span.

 
Header Php align image with text

Set both the span and the image to display: inline-block;

If you want the text dead center then add some padding to the left, equal to the width of the image.

Alternatively

Put the image inside the span

 
Header Php align image with text

And set it to position absolute, so it hangs out the right hand side.

Neither are perfect solutions, but hopefully one will be right for you. 🙂

Источник

Как выровнять текст на изображении (PHP)

На генерируемых, средствами PHP (GDLib), изображениях часто приходится выводить текст. Иногда этот текст нужно выравнивать по-центру, от какой-либо точки или по правому краю. Размер текста, как правило, разного размера, поэтому необходимо выяснить размер текста в пикселях и отнять от точки вывода текста.

Список функций

Основные функции, которые понадобятся для выравнивания текста:

imagettfbbox

array imagettfbbox(float size, float angle, string fontfile, string text) — функция возвращает массив координат прямоугольника в который можно строго вписать надпись string text , размером float size , с наклоном float angle и шрифтом string fontfile .

imagettftext

array imagettftext(resource image, float size, float angle, int x, int y, int color, string fontfile, string text) — функция вывода текста на изображение.

Пример-решение

На примере выведем текст относительно вертикальной линии. По левому краю, по центру и по правому соответственно.

Результат

Выравнивание текст на изображение (PHP)

Категории

Читайте также

  • Узнать цвет пикселя изображения (PHP)
  • Как получить высоту изображения (PHP)
  • Как получить ширину изображения (PHP)
  • Превью в виде квадрата (PHP)
  • Как нарисовать линию (PHP)
  • Как нарисовать круг (PHP)
  • Наложение логотипа (PHP)
  • Как нарисовать прямоугольник (PHP)
  • Как нарисовать эллипс (PHP)
  • Как обновить CDATA (PHP)
  • Singleton Trait (PHP)
  • Редирект (PHP)

Комментарии

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Источник

Оцените статью