ImageTitle.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<?php
/**
* ImageTitle.class.php
*
* La clase se encarga de crear una imagen de un texto dado por el usuario usando una fuente TrueType.
*
* Caracteristicas
* -Si la librer?ia FreeType no esta disponible, se crear?a la imagen usando fuentes del sistema.
* -Permite especificar el color de fondo y del texto. Estos colores se dan en formato HTML.
* -Si se usa una fuente TrueType, permite especificar el tama?nyo de la misma.
* -Si la fuente TrueType indicada no esta disponible, se usar?a una fuente del sistema.
* -Permite poner un fondo degradado mediante el metodo useGradBg(), donde el parametro opcional es el
*  tipo de degradado a usar: 0 - Horizontal, 1 - Vertical, 2 - Rectangular, 3 - Circular.
* -Permite poner un borde a la imagen generada. De momento solo es posible especificar el color.
*
* Ejemplos
*
* Muestra el texto por defecto usando la fuente default. Si no existe, usa fuente del sistema.
* Url de ejemplo: http://stuff.otaku-anime.com/ejImage.php
* <?php
* include("ImageTitle.class.php");
* $img = new ImageTitle;
* $img->showImg();
* ?>
*
* Crea la imagen por un dato pasado por la url. archivo.php?texto=PHP-Hispano
* Url de ejemplo: http://stuff.otaku-anime.com/ejImage.php?ej=1&texto=PHP-Hispano
* <?php
* $texto = isset($_GET['texto']) ? $_GET['texto'] : '' ;
* include("ImageTitle.class.php");
* $img = new ImageTitle;
* $img->setText($texto);
* $img->showImg();
* ?>
*
* Crea una imagen con el fondo azul y el texto rojo.
* Url de ejemplo: http://stuff.otaku-anime.com/ejImage.php?ej=2
* <?php
* include("ImageTitle.class.php");
* $img = new ImageTitle;
* $img->setBgColor("0000FF");
* $img->setFontColor("FF0000");
* ?>
*
* Crea una imagen con un degradado radial de verde hacia azul, un tamanyo de fuente de 50 pixels y un borde.
* Url de ejemplo: http://stuff.otaku-anime.com/ejImage.php?ej=3
* <?php
* include("ImageTitle.class.php");
* $img->new ImageTitle;
* $img->useGradBg(3);
* $img->setGradBgColor("00FF00", "0000FF");
* $img->setFontSize(50);
* $img->useBorder();
* $img->showImg();
* ?>
*
* @author oso96_2000 <oso96.2000@gmail.com>
*/
class ImageTitle {
    
/**
     * Se declaran las variables que se usar?an.
     */
    
var $text;
    var
$fontSize;
    var
$font;
    var
$marginH;
    var
$marginV;
    var
$bgColor;
    var
$fontColor;
    var
$gradientBg;
    var
$gBgStart;
    var
$gBgEnd;
    var
$gType;
    var
$gSize;
    var
$border;
    var
$bColor;
    var
$width;
    var
$height;
    var
$fontFound;
    var
$libFreeType;
    var
$img;
    var
$size;
    var
$incR;
    var
$incG;
    var
$incB;
    
/**
     * Se inicializan las variables.
     */
    
function ImageTitle() {
        
$this->text = "Texto por defecto";
        
$this->fontSize = 20;
        
$this->font = "rabiohead.ttf";
        
$this->marginH = 2;
        
$this->marginV = 2;
        
$this->bgColor = "000000";
        
$this->fontColor = "FFFFFF";
        
$this->gradientBg = false;
        
$this->sGradBg = "9B9B9B";
        
$this->eGradBg = "EFEFEF";
        
$this->gType = 0;
        
$this->gSize = 100;
        
$this->border = false;
        
$this->bColor = "000000";
        
$this->fontFound = file_exists($this->font) ? true : false ;
        
$this->libFreeType = function_exists('imagettftext') ? true : false ;
        if (!
extension_loaded('gd') && !extension_loaded('gd2')) {
            
trigger_error("No dispones de la libreria GD para generar la imagen.", E_USER_WARNING);
            return
false;
        }
    }
    
/**
     * @desc Me?todo con el cual se especifica el texto a escribir en la imagen. Si no existe, se usara? el texto por defecto.
     * @param mixed $text
     */
    
function setText($text = null) {
        
$this->text = !empty($text) ? $text : $this->text ;
    }
    
/**
     * @desc Me?todo para especificar el tamany?o de la fuente que se usara?. Solo aplica si se usa una fuente TrueType.
     * @param int $fs
     */
    
function setFontSize($fs = 20) {
        
$this->fontSize = ereg("^[0-9]+$", $fs) ? $fs : $this->fontSize ;
    }
    
/**
     * @desc Me?todo con el que se especifica la fuente TrueType a usara. Si esta no existe, se usara una fuente del sistema.
     * @param string $ft
     */
    
function setFont($ft = "rabiohead.ttf") {
        if (
file_exists($ft)) {
            
$this->font = $ft;
            
$this->fontFound = true;
        }
    }
    
/**
     * @desc Me?todo para especificar la separacion entre el texto y los bordes, tanto horizontal como vertical.
     * @param int $mH
     * @param int $mV
     */
    
function setMargin($mH = 2, $mV = 2) {
        
$this->marginH = ereg("^[0-9]+$", $mH) ? abs($mH) : $this->marginH ;
        
$this->marginV = ereg("^[0-9]+$", $mV) ? abs($mV) : $this->marginV ;
    }
    
/**
     * @desc M?etodo que especifica el color de fondo de la imagen en formato HTML.
     * @param string $bg
     */
    
function setBgColor($bg = "000000") {
        
$this->bgColor = eregi("([0-9a-f]{2}){3}", $bg) ? $bg : $this->bgColor ;
    }
    
/**
     * @desc M?etodo que especifica el color del texto de la imagen en formato HTML.
     * @param string $tc
     */
    
function setFontColor($tc = "000000") {
        
$this->fontColor = eregi("([0-9a-f]{2}){3}", $tc) ? $tc : $this->fontColor ;
    }
    
/**
     * @desc Metodo para determinar si se usara un borde en la imagen. El parametro determina el color.
     * @param string $c
     */
    
function useBorder($c = "000000") {
        if (
eregi("([0-9a-f]{2}){3}", $c)) {
            
$this->border = true;
            
$this->bColor = $c;
        }
    }
    
/**
     * @desc Metodo para determinar si se usara o no un fondo degradado. El parametro opcional determina el tipo de gradiente.
     * @param int $gT
     */
    
function useGradBg($gT = 0) {
        
$this->gradientBg = true;
        
$this->gType = ereg("^[0-3]$", $gT) ? $gT : $this->gType ;
    }
    
/**
     * @desc Metodo para especificar el color de inicio y final al usar un fondo con degradado.
     * @param string $sBg
     * @param string $eBg
     */
    
function setGradBgColor($sBg = "9B9B9B", $eBg = "EFEFEF") {
        
$this->sGradBg = eregi("([0-9a-f]{2}){3}", $sBg) ? $sBg : $this->sGradBg ;
        
$this->eGradBg = eregi("([0-9a-f]{2}){3}", $eBg) ? $eBg : $this->eGradBg ;
    }
    
/**
     * @desc Metodo que especifica el tamanyo del gradiente. Solo aplica para gradiente rectangular o circular. No se recomienda un valor muy grande.
     * @param int $s
     */
    
function setGradSize($s = 100) {
        
$this->gSize = (ereg("^[0-9]+$", $s) && $s > 0) ? $s : $this->gSize ;
    }
    
/**
     * @desc Crea el fondo gradiente en la imagen dependiendo del tipo escogido.
     * @param int $type
     */
    
function makeGradientBg($type = 0) {
        if (
$this->gradientBg === false)    return false;
        list (
$rGs, $gGs, $bGs) = $this->html2rgb($this->sGradBg);
        list (
$rGe, $gGe, $bGe) = $this->html2rgb($this->eGradBg);
        switch(
$type) {
            case
0:    default: //Gradiente vertical. Por defecto.
                
$incR = ($rGe - $rGs) / $this->height;
                
$incG = ($gGe - $gGs) / $this->height;
                
$incB = ($bGe - $bGs) / $this->height;
                for (
$i = 0; $i < $this->height; $i++) {
                    
imageline($this->img, 0, $i, $this->width, $i, imagecolorallocate($this->img, $rGs, $gGs, $bGs));
                    
$rGs += $incR;
                    
$gGs += $incG;
                    
$bGs += $incB;
                }
            break;
            case
1:    //Gradiente horizontal.
                
$incR = ($rGe - $rGs) / $this->width;
                
$incG = ($gGe - $gGs) / $this->width;
                
$incB = ($bGe - $bGs) / $this->width;
                for(
$i=0; $i < $this->width; $i++) {
                    
imageline($this->img, $i, 0, $i, $this->height, imagecolorallocate($this->img, $rGs, $gGs, $bGs));
                    
$rGs += $incR;
                    
$gGs += $incG;
                    
$bGs += $incB;
                }
            break;
            case
2:    //Gradiente rectangular.
                
$incR = ($rGe - $rGs) / $this->gSize;
                
$incG = ($gGe - $gGs) / $this->gSize;
                
$incB = ($bGe - $bGs) / $this->gSize;
                
$incX = ($this->width / 2) / $this->gSize;
                
$incY = ($this->height / 2) / $this->gSize;
                
$x = $y = 0;
                for (
$i = 0; $i < $this->gSize; $i++) {
                    
imagefilledrectangle($this->img, $x, $y, $this->width - $x, $this->height - $y, imagecolorallocate($this->img, $rGs, $gGs, $bGs));
                    
$rGs += $incR;
                    
$gGs += $incG;
                    
$bGs += $incB;
                    
$x += $incX;
                    
$y += $incY;
                }
            break;
            case
3:    //Gradiente radial.
                
$incR = ($rGe - $rGs) / $this->gSize;
                
$incG = ($gGe - $gGs) / $this->gSize;
                
$incB = ($bGe - $bGs) / $this->gSize;
                
$centerX = $this->width / 2;
                
$centerY = $this->height / 2;
                
$w = $this->width + $this->gSize;
                
$h = $this->height * 2;
                
$incX = $w / $this->gSize;
                
$incY = $h / $this->gSize;
                for (
$i = 0; $i < $this->gSize; $i++) {
                    
imagefilledellipse($this->img, $centerX, $centerY, $w, $h, imagecolorallocate($this->img, $rGs, $gGs, $bGs));
                    
$rGs += $incR;
                    
$gGs += $incG;
                    
$bGs += $incB;
                    
$w -= $incX;
                    
$h -= $incY;
                }
            break;
        }
    }
    
/**
     * @desc Convierte un color en formato HTML a RGB y lo retorna en un arreglo.
     * @param string $color
     * @return array|bool
     */
    
function html2rgb($color = null) {
        return (
$color == null) ? false : array_map('hexdec', function_exists('str_split') ? str_split($color, 2) : preg_split('/([0-9a-f]{2})/i', $color, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)) ;
    }
    
/**
     * @desc Metodo que muestra la imagen en el navegador.
     */
    
function showImg() {
        if (
$this->libFreeType && $this->fontFound === true) {
            
$size = imagettfbbox($this->fontSize, 0, $this->font, $this->text);
            
$this->width = $size[2] + $size[0] + ($this->marginH * 2);
            
$this->height = abs($size[1]) + abs($size[7]) + ($this->marginV * 2);
        }else{
            
$this->width = strlen($this->text) * imagefontwidth(2) + ($this->marginH * 2);
            
$this->height = imagefontheight(2) + ($this->marginV * 2);
        }
        if (
$this->border === true) {
            
$this->width += 2;
            
$this->height += 2;
        }
        
$this->img = function_exists('imagecreatetruecolor') ? imagecreatetruecolor($this->width, $this->height) : imagecreate($this->width, $this->height) ;
        if (
$this->gradientBg === true) {
            
$this->makeGradientBg($this->gType);
        }else{
            list (
$r, $g, $b) = $this->html2rgb($this->bgColor);
            
imagefill($this->img, 0, 0, imagecolorallocate($this->img, $r, $g, $b));
        }
        list (
$r, $g, $b) = $this->html2rgb($this->fontColor);
        
$fontColorImg = imagecolorallocate($this->img, $r, $g, $b);
        if (
$this->libFreeType && $this->fontFound === true)
            
imagettftext($this->img, $this->fontSize, 0, $this->marginH, abs($size[5]) + $this->marginV, $fontColorImg, $this->font, $this->text);
        else
            
imagestring($this->img, 2, $this->marginH, $this->marginV, $this->text, $fontColorImg);
        if (
$this->border === true) {
            list (
$r,$g, $b) = $this->html2rgb($this->bColor);
            
imagerectangle($this->img, 0, 0, $this->width - 1, $this->height - 1, imagecolorallocate($this->img, $r, $g, $b));
        }
        
header("Content-type: image/png");
        
imagepng($this->img);
        
imagedestroy($this->img);
    }
}
?>
PHP-Hispano.net - Porque al final, todos acabamos aprendiendo.