Spanish (Español) translation by Rene Soto (you can also view the original English article)
En el artículo anterior, nos enfocamos en cargar y manipular imágenes con PHP. Aprendimos a rotar, redimensionar, escalar o voltear una imagen. También aprendimos sobre los diferentes filtros y la matriz de convolución. Esos tutoriales también cubrieron algunos usos prácticos de la libreria GD como cambiar el tamaño de todas las imágenes en un directorio o agregar marcas de agua en varias imágenes a la vez.
- PHPManipulando Imágenes en PHP Usando GDMonty Shookeen
- PHPRedimensionar y Manipular Imágenes en PHP (Con Ejemplos)Monty Shokeen
Además de usar GD para manipular imágenes
normales, también podemos crear nuestras propias desde cero. Se pueden usar
diferentes funciones en la librería para dibujar formas básicas como elipses,
círculos, rectángulos, polígonos y líneas simples. Con algunas matemáticas, estas formas pueden
crear patrones agradables. También hay funciones disponibles para dibujar texto
en la imagen renderizada, lo que abre muchas posibilidades.
Este tutorial te enseñará cómo dibujar formas básicas en PHP
y cómo representar texto usando tu fuente favorita.
Dibujar formas básicas en PHP con GD
Aprenderemos sobre formas básicas en esta sección y luego cubriremos el grosor de línea, los pinceles y los estilos de línea más adelante.
Dibujar Lineas
Puedes dibujar una línea recta simple entre dos
puntos dados usando la función imageline ($imagen, $x1, $y1, $x2, $y2, $color)
. El parámetro $image
es un recurso de imagen que
se habrá creado anteriormente utilizando funciones como imagecreatetruecolor ()
o imagecreatefromjpeg ()
. Usaremos imagecreatetruecolor ()
en este tutorial para crear
nuevas imágenes desde cero. La función dibujará una línea horizontal si $y1
es
igual a $y2
. De manera similar, dibujará una línea vertical si $x1
es igual a
$x2
.
Dibujar Circulos y Arcos
La función imagearc ($image, $cx, $cy, $width,
$height, $start, $end, $color)
puede dibujar arcos circulares utilizando $cx
y $cy
como su centro. Los parámetros $width
y $height
determinan el tamaño del arco
en diferentes ejes. Los parámetros $start
y $end
especifican el ángulo de inicio
y final del arco en grados. Si deseas dibujar arcos completos de 0 a 360 grados,
puedes usar la función alternativa imageellipse ($image, $cx, $cy, $width,
$height, $color)
.
Dibujar Rectángulos y Polígonos
Puedes dibujar rectángulos sobre una imagen
usando la función imagerectangle ($image, $x1, $y1, $x2, $y2, $color)
. Los valores
$x1
y $y1
determinan la esquina superior izquierda del rectángulo. Los valores $x2
y $y2
determinan la esquina
inferior derecha. También hay una función imagepolygon ($image, $points,
$num_points, $color)
, que puede crear un polígono con cualquier número de lados
o puntos. El parámetro $points
es una matriz donde dos elementos se
emparejan para obtener las coordenadas de un punto específico.
Otra función llamada imageopenpolygon()
se ha agregado a PHP
7, que no dibuja una línea entre el primer y el último punto.
Juntándolo para Crear un Dibujo
En el siguiente ejemplo, hemos utilizado todas estas
funciones para crear un dibujo lineal con una cabaña, el sol y el suelo.
<?php header("Content-type: image/png"); $img_width = 800; $img_height = 600; $img = imagecreatetruecolor($img_width, $img_height); $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $red = imagecolorallocate($img, 255, 0, 0); $green = imagecolorallocate($img, 0, 255, 0); $blue = imagecolorallocate($img, 0, 0, 255); $orange = imagecolorallocate($img, 255, 200, 0); imagefill($img, 0, 0, $white); imagerectangle($img, $img_width*2/10, $img_height*5/10, $img_width*4/10, $img_height*8/10, $red); imagerectangle($img, $img_width*4/10, $img_height*5/10, $img_width*8/10, $img_height*8/10, $red); imagepolygon($img, [$img_width*3/10, $img_height*2/10, $img_width*2/10, $img_height*5/10, $img_width*4/10, $img_height*5/10], 3, $red); imageopenpolygon($img, [$img_width*3/10, $img_height*2/10, $img_width*7/10, $img_height*2/10, $img_width*8/10, $img_height*5/10], 3, $red); imageellipse($img, 100, 100, 100, 100, $orange); imagearc($img, $img_width*3/10, $img_height*8/10, 100, 200, 180, 360, $red); imageline($img, 0, $img_height*8/10, $img_width, $img_height*8/10, $green); imagepng($img); ?>
Lo importante aquí es simplemente averiguar el valor de las diferentes coordenadas. Quería dibujar todo en relación con el tamaño de la imagen original, así que usé las variables $img_height
e $img_width
para calcular las coordenadas de diferentes puntos.



Control del Grosor de Línea, Estilo y Rellenos de Color
La imagen de arriba tiene un par de problemas como líneas muy finas y sin colorear. Todos estos problemas pueden solucionarse fácilmente mediante funciones como imagesetthickness()
e imagefilledrectangle()
.
Grosor de la línea
La función de imagesetthickness($image, $thickness)
establece el grosor de las líneas renderizadas al dibujar rectángulos, polígonos, arcos, etc. Por ejemplo, si se configura $thickness
a 5, cualquier figura dibujada utilizando imagerectangle()
, imagearc()
, imagepolygon()
, etc. 5 píxeles de espesor.
Dibujando Formas Rellenas
Cada función de dibujo también tiene una versión de color rellena que llena esa figura en particular con un color determinado. Por ejemplo, imagefilledrectangle()
llenará el rectángulo dibujado con el color dado.
Utilizando Pinceles
Una función GD muy útil es imagesetbrush
($image, $brush)
. El parámetro $brush
en esta función es solo otro recurso de
imagen que se puede usar para dibujar líneas. Por ejemplo, puedes usar un dibujo vectorial
transparente de una flor como un pincel para agregar bonitos patrones de flores
a tu imagen. El fragmento de código que se proporciona a
continuación fue escrito para usar la imagen de una nube como un pincel al
dibujar un punto. Esto agrega una sola nube en nuestro cielo.
<?php $img = imagecreatetruecolor($img_width, $img_height); $clouds = imagecreatefrompng('clouds.png'); $clouds = imagescale($clouds, 250); imagesetthickness($img, 5); imagesetbrush($img, $clouds); imageline($img, $img_width*9/10, 50, $img_width*9/10, 50, IMG_COLOR_BRUSHED); ?>
Encontré esta imagen de una nube en Pixabay y la reduje a un tamaño apropiado para nuestro proyecto.
El código completo para la imagen de la choza se da a continuación. Simplemente hemos agregado dos versiones de cada figura, una para dibujar el contorno y la otra para completar el color.
<?php header("Content-type: image/png"); $img_width = 800; $img_height = 600; $img = imagecreatetruecolor($img_width, $img_height); $clouds = imagecreatefrompng('clouds.png'); $clouds = imagescale($clouds, 250); imagesetthickness($img, 5); imagesetbrush($img, $clouds); $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $red = imagecolorallocate($img, 255, 0, 0); $green = imagecolorallocate($img, 0, 255, 0); $blue = imagecolorallocate($img, 0, 200, 250); $orange = imagecolorallocate($img, 255, 200, 0); $brown = imagecolorallocate($img, 220, 110, 0); imagefill($img, 0, 0, $white); imagefilledrectangle($img, 0, 0, $img_width, $img_height*8/10, $blue); imagefilledrectangle($img, $img_width*2/10, $img_height*5/10, $img_width*4/10, $img_height*8/10, $red); imagefilledrectangle($img, $img_width*4/10 - 2, $img_height*5/10, $img_width*8/10, $img_height*8/10, $red); imagefilledpolygon($img, [$img_width*3/10, $img_height*2/10, $img_width*2/10, $img_height*5/10, $img_width*4/10, $img_height*5/10], 3, $red); imagefilledpolygon($img, [$img_width*3/10, $img_height*2/10, $img_width*7/10, $img_height*2/10, $img_width*8/10, $img_height*5/10, $img_width*4/10, $img_height*5/10], 4, $red); imagefilledarc($img, 100, 100, 100, 100, 0, 360, $orange, IMG_ARC_PIE); imagefilledarc($img, $img_width*3/10, $img_height*8/10, 100, 200, 180, 360, $brown, IMG_ARC_PIE); imagefilledrectangle($img, 0, $img_height*8/10, $img_width, $img_height, $green); imagerectangle($img, $img_width*2/10, $img_height*5/10, $img_width*4/10, $img_height*8/10, $black); imagerectangle($img, $img_width*4/10 - 2, $img_height*5/10, $img_width*8/10, $img_height*8/10, $black); imagepolygon($img, [$img_width*3/10, $img_height*2/10, $img_width*2/10, $img_height*5/10, $img_width*4/10, $img_height*5/10], 3, $black); imageopenpolygon($img, [$img_width*3/10, $img_height*2/10, $img_width*7/10, $img_height*2/10, $img_width*8/10, $img_height*5/10], 3, $black); imagearc($img, 100, 100, 100, 100, 0, 360, $black); imagearc($img, $img_width*3/10, $img_height*8/10, 100, 200, 180, 360, $black); imageline($img, $img_width*9/10, 50, $img_width*9/10, 50, IMG_COLOR_BRUSHED); imagerectangle($img, -100, $img_height*8/10, $img_width*11/10, $img_height*11/10, $black); imagepng($img); ?>
Este es el resultado final del código PHP GD anterior.



Renderizar Texto en Imágenes
PHP GD viene con cuatro funciones
diferentes que te permiten representar múltiples caracteres o solo un carácter
en una dirección horizontal o vertical. Estas funciones son imagechar()
, imagecharup()
, imagestring()
e imagestringup()
. Todos ellos aceptan los mismos seis
parámetros, por lo que solo discutiremos la función imagechar()
aquí.
El parámetro $font
imagechar ($image, $font, $x,
$y, $string, $color)
es simplemente el tamaño del texto representado. Solo
acepta valores enteros del 1 al 5. El parámetro $string
es el texto que desea
procesar. Si pasa una cadena de caracteres múltiples a las
funciones char, solo se representará el primer carácter en la imagen. Las
funciones imagecharup()
e imagestringup ()
representarán el texto
verticalmente de abajo hacia arriba.
Cuando se trata de representar texto, las cuatro funciones que discutimos anteriormente son muy limitadas. Encontrarás que incluso el valor de tamaño de fuente más grande es demasiado pequeño para el uso normal.
Afortunadamente, GD también tiene una función
imagettftext ($image, $size, $angle, $x, $y, $color, $fontfile, $text)
que
puede representar el texto en cualquier fuente que desee. El parámetro $fontfile
se usa para especificar la ruta a la fuente TrueType que desea usar para mostrar el texto. Los parámetros $x
y $y
determinan la posición inicial del texto representado.
El siguiente ejemplo utiliza todas estas funciones para crear algunos efectos de texto agradables.
<?php header("Content-type: image/png"); $img_width = 800; $img_height = 600; $img = imagecreatetruecolor($img_width, $img_height); $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $red = imagecolorallocate($img, 255, 0, 0); $green = imagecolorallocate($img, 0, 255, 0); $blue = imagecolorallocate($img, 0, 200, 250); $orange = imagecolorallocate($img, 255, 200, 0); $brown = imagecolorallocate($img, 220, 110, 0); imagefill($img, 0, 0, $white); imagestringup($img, 5, $img_width*19/20, $img_height*19/20, 'This sentence was written using imagestringup()!', $blue); imagestring($img, 5, $img_width/20, $img_height/20, 'This sentence was written using imagestring()!', $red); $passion_one = dirname(__FILE__) . '/PassionOne-Regular.ttf'; imagettftext($img, 32, 0, $img_width/20, $img_height*2/10, $black, $passion_one, 'This is Passion One Font!'); $merriweather = dirname(__FILE__) . '/Merriweather-Regular.ttf'; imagettftext($img, 24, 90, $img_width*9/10, $img_height*19/20, $black, $merriweather, 'This is Merriweather Regular Font!'); $patua_one = dirname(__FILE__) . '/PatuaOne-Regular.ttf'; imagettftext($img, 32, 0, $img_width/20, $img_height*3/10 + 2, $black, $patua_one, 'This is Patua One Font!'); imagettftext($img, 32, 0, $img_width/20, $img_height*3/10, $orange, $patua_one, 'This is Patua One Font!'); $monoton = dirname(__FILE__) . '/Monoton-Regular.ttf'; imagettftext($img, 72, 0, $img_width/20, $img_height*5.5/10 - 5, $brown, $monoton, 'MONOTON'); imagettftext($img, 72, 0, $img_width/20, $img_height*5.5/10 + 5, $orange, $monoton, 'MONOTON'); imagettftext($img, 72, 0, $img_width/20, $img_height*5.5/10, $blue, $monoton, 'MONOTON'); $kaushan = dirname(__FILE__) . '/KaushanScript-Regular.ttf'; imagettftext($img, 84, 0, $img_width/20, $img_height*8/10 - 2, $brown, $kaushan, 'Good Night!'); imagettftext($img, 84, 0, $img_width/20, $img_height*8/10 + 2, $black, $kaushan, 'Good Night!'); imagettftext($img, 84, 0, $img_width/20 - 2, $img_height*8/10, $brown, $kaushan, 'Good Night!'); imagettftext($img, 84, 0, $img_width/20 + 2, $img_height*8/10, $black, $kaushan, 'Good Night!'); imagettftext($img, 84, 0, $img_width/20, $img_height*8/10, $white, $kaushan, 'Good Night!'); imagepng($img); ?>
Como puedes ver, hemos renderizado el mismo texto con la misma fuente en posiciones ligeramente diferentes para crear algunos efectos como la sombra del texto básico. Lo importante a tener en cuenta es que el texto representado por cualquier función de texto ocultará completamente el texto debajo en caso de que se superponga. Aquí está la imagen final obtenida después de ejecutar el código anterior.



Pensamientos Finales
El objetivo de este tutorial era familiarizarte con las diferentes funciones de GD para dibujar formas básicas desde cero en PHP. Con la ayuda de un poco de matemáticas, podrás usar estas funciones para crear formas más complicadas como polígonos regulares, rectángulos redondeados, etc.
PHP GD también tiene un par de funciones muy útiles para representar texto en una imagen. El uso de una fuente agradable asegurará que el texto representado no se vea extraño cuando se coloca en imágenes normales cargadas desde diferentes rutas de archivo.
¿Creaste efectos de texto más sofisticados en
PHP? Por favor, comparte con nosotros en los comentarios