GithubHelp home page GithubHelp logo

gd-text's People

Contributors

bradfora avatar hjanuschka avatar liviucmg avatar stil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gd-text's Issues

Max text width and height

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.

Call to undefined function GDText\imageftbbox()

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!

setLeading() doesn't exist

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

Reverse lines order in Persian and Arabic text wrap

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:

Bang

So we have to use a library like persian phpgd by @slashmili which will return an output like:

Reverse

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);
   }

So the output will correctly be:
Correct

Bad text shadow

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;
}

Before

thumb_bad

After

thumb_ok

Could not find/open font

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..

Arabic language support !

Do this package support Arabic language, when I write text on image in Arabic , i get inversed direction and letters separated

TestCase Not Found Error

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

Use code in a basic php

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.

Font size dependent on image size (px)

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)

Calculate the text height and width

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?

How do I set multiple paragraphs

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?

Set 2 fonts with different text in the same draw function?

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

UTF-8 Support

Hi, gd-text not supporting utf-8. Promptly it need to fix. Otherwise I will have to choose another framework.

strokeText is too slow!

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);
    }

Problem with function "drawFitFontSize"

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^

Chinese Language

how is the support for other languages such as Chinese? I have tried on my side but its not working well. It overflows.

Set padding

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.

No issue. just thanks.

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.

Combine with intervention Images

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

Last line different alignment?

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?

Font size calculating

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.

Color Index when adding text to existing PNG or GIF

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?

Installation through composer

  • Installation request for stil/gd-text ^1.1 -> satisfiable by stil/gd-text[v1.1.0].
    stil/gd-text v1.1.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.

No example how to use it

You script look interesting but there's no example how to use it.

Can you provide some example?

Can't installing via composer

Problem 1:

  • The requested package stil/gd-text No version set (parsed as 1.0.0) is satisfiable by stil/gd-text[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.

I'm running on WAMP, apache 2.4.23, php 7.0.10. Any ideas?

Justified alignment

Would it be possible to have an extra alignment type (fully justified text) ?

Thanks,

New API allowing for per-line formatting, public methods for text measurement

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:
demo_lineheight php

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.