Re: [GD-DEVEL] GD Question
[email protected] (Derick Rethans)
| Newsgroups | php.gd.devel |
|---|---|
| Message-ID | <[email protected]> |
On Thu, 3 Jan 2008, Tony wrote: > Hello. I wanted to ask if there is a way to write a text string to a JPEG > image such that the foreground color will always be visible regardless of the > underlying image? I've some code that analyses the background colour and draw the text on top of it in a readable colour. It works moderately well - it's written in PHP. This little script (attached) does it by word even, you will probably have to tweak it. Derick -- Derick Rethans http://derickrethans.nl | http://ezcomponents.org | http://xdebug.org
l.php
(text/plain, 2 KB)
<?php
$text = "© ". date('Y'). " - Derick Rethans - All rights reserved";
$font = "/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf";
$fs = 8;
$im = imagecreatefromjpeg($argv[1]);
$xp = imagesx($im) - 270;
$yp = imagesy($im) - 5;
/*
$xp = 20 + rand(0, imagesx($im) - 270);
$yp = 20 + rand(0, imagesy($im) - 40);
*/
$text = preg_split('/\s/', $text);
$strlen = count($text);
$x = $xp;
for ($i = 0; $i < $strlen; $i++) {
drawtext($im, $x, $yp, $text[$i]);
$a = imagettfbbox($fs, 0, $font, $text[$i]);
$x += $a[2] - $a[0] + 6;
}
header('Content-Type: image/jpg');
imagejpeg($im, '', 85);
function drawtext($im, $xp, $yp, $text)
{
$font = "/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf";
$fs = 8;
$a = imagettfbbox($fs, 0, $font, $text);
$cb = imagecolorallocate($im, 0, 0, 0);
$cw = imagecolorallocate($im, 250, 250, 250);
$l = 0;
$lc = 0;
for ($x = $a[0] + 1; $x <= $a[2]; $x++) {
for ($y = $a[5]; $y < $a[1]; $y++) {
$l += imagelightnessat($im, $xp + $x, $yp + $y);
$lc++;
}
}
if ($lc > 0) {
$l = $l / $lc;
if ($l >= 0.00 and $l < 0.25) $c = 150;
if ($l >= 0.25 and $l < 0.33) $c = 250;
if ($l >= 0.33 and $l < 0.40) $c = 250;
if ($l >= 0.40 and $l < 0.60) $c = 20;
if ($l >= 0.60 and $l < 0.80) $c = 40;
if ($l >= 0.80 and $l < 1.00) $c = 60;
$tc = imagecolorallocate($im, $c, $c, $c);
imagettftext($im, $fs, 0, $xp, $yp, $tc, $font, $text);
}
}
function imagelightnessat($img, $x, $y)
{
$c = imagecolorat($img, $x, $y);
if ($c === false) {
return false;
}
$red = ($c >> 16) & 0xFF;
$green = ($c >> 8) & 0xFF;
$blue = $c & 0xFF;
$m = min($red, $green, $blue);
$n = max($red, $green, $blue);
/* Because RGB isn't normalized in GD, we divide by 510 here.
* Lightness = (Max(RGB) + Min(RGB)) / 2
* But that's assuming red, green, and blue are 0 through 1 inclusive.
* Red, green, and blue are actually 0-255 (255 + 255 = 510).
*/
$lightness = (double)(($m + $n) / 510.0);
return $lightness;
}