stil / gd-text Goto Github PK
View Code? Open in Web Editor NEWPHP class making it easy to type text on pictures. Supports multi-lined text, horizontal and vertical alignment.
PHP class making it easy to type text on pictures. Supports multi-lined text, horizontal and vertical alignment.
please am new to composer and it really strange to me, please hw can i use these library in my web app .
please help me, thanks
Hi I want to use the project to write text on an image inside a box. So I need a function where I can set max width and height of the text not just max width and height of the textbox. So it should scale down the text until it fits inside the box.
I don't know how to use gd-text, I can't get defined the imageftbbox function. I think I have all php and gd installed but it's impossible to run this.
The error I get:
Fatal error: Call to undefined function GDText\imageftbbox() in /vendor/stil/gd-text/src/Box.php on line 383
Does anybody know how can I do?
Thank you!
Hiya,
I noticed the examples in the README reference a setLeading()
method, but it looks like that method doesn't actually exist. Are you planning to implement it?
Cheers, Craig
Great library.Keep it up . I am using it on our site.Very Helpful.Can I add Font Styles like Bold,Italic or give it some Stroke.
Is there a method to change the text color per character?
Maybe this is not an issue but it can be a helpful answer that can save time for programmers who are speaking Persian (Farsi) or Arabic.
As you know, we cannot directly pass Persian (or Arabic) to $box->draw
which $box is an instance of GDText::Box
.
For example, if we have a text like:
همدان قدیمیترین شهر ایران و از کهنترین شهرهای جهان است. نخستین باری
که اسم این شهر برده شد، در حدود ۱۱۰۰ سال پیش از میلاد بود که نام همدان
را اَمدانه ذکر شدهاست.
and we directly pass it to the box, it will be like:
So we have to use a library like persian phpgd
by @slashmili which will return an output like:
Natives know that the output is in reverse order.
را امدانه ذکر شده است
از میلاد بود که نام همدان
در حدود ۱۱۰۰ سال پیش
که اسم این شهر برده شد،
جهان است. نخستین باری
ایران و از کهنترین شهرهای
همدان قدیمیترین شهر
It should be:
همدان قدیمیترین شهر
ایران و از کهنترین شهرهای
جهان است. نخستین باری
که اسم این شهر برده شد،
در حدود ۱۱۰۰ سال پیش
از میلاد بود که نام همدان
را امدانه ذکر شده است
Solution
So changes are required in Box.php
:
+ /**
+ * @var reverse_text_lines_order
+ */
+ protected $reverse_text_lines_order = false;
+ /**
+ * @param bool $reverse_text_lines_order To Reverse Lines Order
+ */
+ public function setReverseTextLinesOrder($reverse_text_lines_order)
+ {
+ $this->reverse_text_lines_order = $reverse_text_lines_order;
+ }
Then use the new prop inside draw
function:
}
$lines[] = $line;
}
+ if ($this->reverse_text_lines_order == true)
+ $lines = array_reverse($lines);
return $lines;
}
In your main class you have to detect Persian (or Arabic) with following regex and then pass a parameter to $box
:
if (preg_match('/.*[چﺞﺤﺨﻬﻌﻐﻔﻘﺜﺼﻀﺸﺳیﺏﻼﺘﻨﻣکگﻭپﺩﺫﺭﺰﻄﻇژ].*/u', $text)){
$text = fagd($input,'fa','vazir');
$box->setReverseTextLinesOrder(true);
}
Hi,
When creating text within a white background, text shadow gets badly shaped (at least for me). To solve it, i rewrote the "Color->getIndex()" function. It works fine for me now:
/**
* @param resource $image GD image resource
* @return int Returns the index of the specified color+alpha in the palette of the image,
* or -1 if the color does not exist in the image's palette.
*/
public function getIndex($image)
{
$color = -1;
if ($this->hasAlphaChannel()) {
if(($color = imagecolorexactalpha(
$image,
$this->red,
$this->green,
$this->blue,
$this->alpha
)) == -1){
$color = imagecolorallocatealpha(
$image,
$this->red,
$this->green,
$this->blue,
$this->alpha
);
}
} else {
if(($color = imagecolorexact(
$image,
$this->red,
$this->green,
$this->blue
)) == -1){
$color = imagecolorallocate(
$image,
$this->red,
$this->green,
$this->blue
);
}
}
return $color;
}
I created this project but i'm taking error..
Error: Could not find/open font / OR / Invalid font filename
Also I'm taking a black screenshot
What should i do?
thanks..
Do this package support Arabic language, when I write text on image in Arabic , i get inversed direction and letters separated
Fatal error: Uncaught Error: Class "GDText\Tests\TestCase" not found in C:\xampp\htdocs\GDTEXT\vendor\stil\gd-text\tests\TextAlignmentTest.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\GDTEXT\vendor\stil\gd-text\tests\TextAlignmentTest.php on line 10
Hello,
How could I use this code in a basic PHP? I just want to use a form to put name and author and generated.
I had copied and pasted the code into a new .php but apparently this code needs a framework for living.
I just want to use it for a very basic code , how can I use it?
A greeting,
Angel.
Is there any function to setFontSize dependent on image size (px) ?
I want the text to be extended (fontsize set) over the whole width of the image (and height - multiline)
Hi, first really big applause for this amazing work. Actually I need to ask, can we calculate the height and width for given text before drawing?
Mean suppose we got dynamic text, can we get the width and height relative to text?
Like how will I know at which coordinate the first paragraph has an end and set the box size accordingly for the 2nd para and onwards?
Basically, I'm trying to create a dynamic image like this How can I set the box size for "Hello!", then the next line and so on?
Why calculateBox() is not a public method?
@liviucmg @stil @hjanuschka @web2033
How can i write the tamil fonts in image. please advice....
imageftbbox(): Could not set character size some of fonts when i test them
error line return imageftbbox($this->getFontSizeInPoints(), 0, $this->fontFace, $text);
Hi, how can I display 2 different fonts in the same text separated by a new line?
$font1 = "font1.ttf";
$font2 = "font2.ttf";
$text1 = "text";
$text2 = "text2";
$box = new Box($im);
$box->setFontFace($font1);
$box->setFontColor(new Color(255, 255, 255));
$box->setTextShadow(new Color(0, 0, 0, 50), 2, 2);
$box->setFontSize(35);
$box->setBox(100, 150, 500, 400);
$box->setTextAlign('center', 'center');
$box->draw($text1."\n".$text2); // here only displays the second text with the font1
Hi, gd-text not supporting utf-8. Promptly it need to fix. Otherwise I will have to choose another framework.
strokeText is very slow for high input (eg 10).
The following code is much more efficient (up to 40 times faster for strokeText = 10)
protected function strokeText($x, $y, $text)
{
$size = $this->strokeSize;
if ($size <= 0) return;
/*
// Current algorithm
for ($c1 = $x - $size; $c1 <= $x + $size; $c1++) {
for ($c2 = $y - $size; $c2 <= $y + $size; $c2++) {
$this->drawInternal(new Point($c1, $c2), $this->strokeColor, $text);
}
}
*/
$tmp_box = $this->calculateBox($text);
$textWidth = $tmp_box->getWidth();
$textHeight = 1.5 * $tmp_box->getHeight();
$tmp_img = imagecreatetruecolor($textWidth, $textHeight);
imagesavealpha($tmp_img, true);
imagefill($tmp_img, 0, 0, imagecolorallocatealpha($tmp_img, 0, 0, 0, 127));
imagettftext(
$tmp_img,
$this->getFontSizeInPoints(),
0, // no rotation
0,
$tmp_box->getHeight(),
$this->strokeColor->getIndex($tmp_img),
$this->fontFace,
$text
);
for ($c1 = $x - $size; $c1 <= $x + $size; $c1++) {
for ($c2 = $y - $size; $c2 <= $y + $size; $c2++) {
imagecopy($this->im, $tmp_img, $c1, $c2 - $tmp_box->getHeight(), 0, 0, $textWidth, $textHeight);
}
}
imagedestroy($tmp_img);
}
I've got problem with drawFitFontSize - works till go closer to border (when fontSize is bigger or text longer) - then 503 error or:
Fatal error: Maximum execution time of 300 seconds exceeded in XXX/public_html/gdtext/vendor/stil/gd-text/src/Box.php on line 476
I'm using #30
Function draw works well
Function should reduce the size of text, but something is wrong and results is 503/statement up^
how is the support for other languages such as Chinese? I have tried on my side but its not working well. It overflows.
I can't find help on how to install gd-text? it looks it's depending on something else.
Hi, first time writing.
Is there a way to set padding to control the background color?
It could be great for styling bloc text deeper.
I have absolutely no problems using this class. Straight in with composer and within 1 hour I'd built a meme generator.
I cannot thank you enough for making this public. If I had to do this with pure GD, I would still be working on the project next month.
Is there any way to align the text as "justify"?
Hello , i was Trying to Make blur to image using intervention images then pass to gd text to add text
was wonder if this possible and how to implement the two libraries to work together maybe to achieve what i want
Hello,
When I am writing hindi text on the image that will show in square block.
Can you let me know how to wrote multi language text on image.
https://ibb.co/17mYqSs
Thanks in advance.
in Arabic language this disconnect letters and change order of lines
I want to have a block of text center vertically and horizontally, and then after it a line that is right aligned, is this possible?
Is there any way to change the orientation from horizontally to vertically?
font: https://fonts.google.com/specimen/Khmer
I have type: ខ្មែរ but working not good
Error: https://www.dropbox.com/s/wyfyuc1erzwei0x/khmer_error.jpg?dl=0
Since we already have a drawFilledRectangle method, this is pretty trivial to do. :) Will make a PR soon.
Could you add the adaptability of the size of the font.
Calculating the size of the font depending on the length of the text. This will allow small texts to see more clearly, bigger.
I don't see anywhere how I can specify using an already indexed color (if I know only the index), can it be done?
Also, what happens if the color palette is already full & you try to assign a new color?
can i use this on native PHP ?
Hi background Can I add any image I want?
You script look interesting but there's no example how to use it.
Can you provide some example?
Problem 1:
I'm running on WAMP, apache 2.4.23, php 7.0.10. Any ideas?
Would it be possible to have an extra alignment type (fully justified text) ?
Thanks,
Need rounded corner feature!
Is it possible to set the text rotation?
There are several open issues asking for text measurement. I want to propose new API for upcoming gd-text release and I invite you to discuss.
class VirtualTextLine
{
/** @return string */
public function getText();
/** @param string $text */
public function setText($text);
/** @return string */
public function getFontFile();
/** @param string $fontFile */
public function setFontFile($fontFile);
/** @return float */
public function getFontSizePx();
/** @return float */
public function getFontSizePt();
/** @param float $fontSizePx */
public function setFontSizePx($fontSizePx);
/** @param float $fontSizePt */
public function setFontSizePt($fontSizePt);
/** @return Rectangle */
public function measureBox();
}
class RichTextLine extends VirtualTextLine
{
/** @return Color */
public function getFontColor();
/** @param Color $color Font color */
public function setFontColor(Color $color);
/** @return Color */
public function getBackgroundColor();
/** @param Color $color Font color */
public function setBackgroundColor(Color $color);
/** @return Color */
public function getTextShadowColor();
/** @return Point */
public function getTextShadowOffset();
/** @return bool */
public function hasTextShadow();
/**
* @param Color $color
* @param int $x
* @param int $y
*/
public function setTextShadow(Color $color, $x, $y);
/** @return int */
public function getStrokeSize();
/** @return Color */
public function getStrokeColor();
/** @return bool */
public function hasStroke();
/** @param Color $color Stroke color */
public function setStrokeColor(Color $color);
/** @param int $v Stroke size in *pixels* */
public function setStrokeSize($v);
/**
* @param Color $color
* @param $size
*/
public function setStroke(Color $color, $size);
/** @return string */
public function getHorizontalAlignment();
/** @param string $horizontalAlignment */
public function setHorizontalAlignment($horizontalAlignment);
/** @return float */
public function getBaseline();
/** @return float */
public function getLineHeight();
/** @param float $v */
public function setLineHeight($v);
/** @param float $v Position of baseline, in percents, proportionally to line height measuring from the bottom. */
public function setBaseline($v);
}
class TextBox
{
/** @param string $verticalAlignment Vertical alignment. Allowed values are: top, center, bottom. */
public function setVerticalContentAlignment($verticalAlignment = VerticalAlignment::Top);
/**
* TextBlock constructor.
* @param resource $img Image resource identifier.
* @param Rectangle $bounds (x, y, width, height) (Distance in pixels from left edge of image, from top edge, width of textbox in pixels, height).
*/
public function __construct($img, Rectangle $bounds);
/** Enables debug mode. Whole textbox and individual lines will be filled with random colors. */
public function enableDebug();
/**
* Draws the text on the picture.
* @param RichTextLine|RichTextLine[] $text Text to draw.
*/
public function draw($text);
}
class TextWrapper
{
/**
* @param VirtualTextLine|RichTextLine $virtualTextLine
* @param Rectangle $bounds
* @return RichTextLine[]|VirtualTextLine[]
*/
public function wrapTextWithOverflow(VirtualTextLine $virtualTextLine, Rectangle $bounds);
Example of new API usage:
// Demo multilined text.
$text = new VirtualTextLine();
$text->setText(" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla eleifend congue auctor. Nullam eget blandit magna. Fusce posuere lacus at orci blandit auctor. Aliquam erat volutpat. Cras pharetra aliquet leo. Cras tristique tellus sit amet vestibulum ullamcorper. Aenean quam erat, ullamcorper quis blandit id, sollicitudin lobortis orci. In non varius metus. Aenean varius porttitor augue, sit amet suscipit est posuere a. In mi leo, fermentum nec diam ut, lacinia laoreet enim. Fusce augue justo, tristique at elit ultricies, tincidunt bibendum erat.\n\n Aenean feugiat dignissim dui non scelerisque. Cras vitae rhoncus sapien. Suspendisse sed ante elit. Duis id dolor metus. Vivamus congue metus nunc, ut consequat arcu dapibus vel. Ut sed ipsum sollicitudin, rutrum quam ac, fringilla risus. Phasellus non tincidunt leo, sodales venenatis nisl. Duis lorem odio, porta quis laoreet ut, tristique a justo. Morbi dictum dictum est ut facilisis. Duis suscipit sem ligula, at commodo risus pulvinar vehicula. Sed quis quam ac quam scelerisque dapibus id non justo. Sed mollis enim id neque tempus, a congue nulla blandit. Aliquam congue convallis lacinia. Aliquam commodo eleifend nisl a consectetur.\n\n Maecenas sem nisl, adipiscing nec ante sed, sodales facilisis lectus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut bibendum malesuada ipsum eget vestibulum. Pellentesque interdum tempor libero eu sagittis. Suspendisse luctus nisi ante, eget tempus erat tristique sed. Duis nec pretium velit. Praesent ornare, tortor non sagittis sollicitudin, dolor quam scelerisque risus, eu consequat magna tellus id diam. Fusce auctor ultricies arcu, vel ullamcorper dui condimentum nec. Maecenas tempus, odio non ullamcorper dignissim, tellus eros elementum turpis, quis luctus ante libero et nisi.\n\n Phasellus sed mauris vel lorem tristique tempor. Pellentesque ornare purus quis ullamcorper fermentum. Curabitur tortor mauris, semper ut erat vitae, venenatis congue eros. Ut imperdiet arcu risus, id dapibus lacus bibendum posuere. Etiam ac volutpat lectus. Vivamus in magna accumsan, dictum erat in, vehicula sem. Donec elementum lacinia fringilla. Vivamus luctus felis quis sollicitudin eleifend. Sed elementum, mi et interdum facilisis, nunc eros suscipit leo, eget convallis arcu nunc eget lectus. Quisque bibendum urna sit amet varius aliquam. In mollis ante sit amet luctus tincidunt.");
$text->setFontFile(__DIR__ . '/fonts/Minecraftia-Regular.ttf');
$text->setFontSizePx(8);
$textBounds = new Rectangle(20, 40, 460, 460);
$textWrapper = new TextWrapper();
$lines = $textWrapper->wrapTextWithOverflow($text, $textBounds);
foreach ($lines as $i => $line) {
$line->setTextShadow(new Color(15, 15, 15), 1, 1);
$line->setLineHeight($lineHeight);
$line->setBaseline(-0.3);
$line->setFontColor(new Color($i * 8, 75, 140));
}
$textBox = new TextBox($im, $textBounds);
$textBox->setVerticalContentAlignment(VerticalAlignment::Top);
$textBox->draw($lines);
Such API allows for individual control over lines formatting, like in example below:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.