Continúe con su entrenamiento y añade alguna funcionalidad a nuestro script.
In the previous lesson, we created an empty function and registered it with GIMP. In this lesson, we want to provide functionality to our script — we want to create a new image, add the user's text to it and resize the image to fit the text exactly.
Once you know how to set variables, define functions and access list members, the rest is all downhill — all you need to do is familiarize yourself with the functions available in GIMP's procedural database and call those functions directly. Open the Sección 12.9, “El visor de procedimientos”.
Comience creando una imagen nueva. Cree una nueva variable, theImage
, es el resultado de llamar a la función de construcción gimp-image-new
de GIMP.
As you can see from the DB Browser, the function
gimp-image-new
takes three parameters — the
image's width, height and the type of image. Because we'll
later resize the image to fit the text, we'll make a 10×10 pixels
RGB
image. We'll store the image's width and sizes in some
variables, too, as we'll refer to and manipulate them later in
the script.
(define (script-fu-text-box inText inFont inFontSize inTextColor) (let* ( ; definir nuestras variables locales ; crear una imagen nueva: (theImageWidth 10) (theImageHeight 10) (theImage (car (gimp-image-new theImageWidth theImageHeight RGB ) ) ) (theText) ;una declaración para el texto ;creamos después
Nota: se usa el valor RGB
para especificar que la imagen es una imagen RGB
. Se podría usar también 0
, pero RGB
es más descriptivo cuando revisamos el código.
You should also notice that we took the head of the result of the function call. This may seem strange, because the database explicitly tells us that it returns only one value — the ID of the newly created image. However, all GIMP functions return a list, even if there is only one element in the list, so we need to get the head of the list.
Ahora que tenemos una imagen, necesitamos añadirle una capa. Llamaremos a la función gimp-layer-new
para crear la capa, basada en el ID de la imagen que hemos creado. (Por ahora, en lugar de listar la función completa, solo listamos las líneas que estamos añadiendo. Puede ver el script completo aquí.) Debido a que hemos declarado las variables locales que usaremos, también cerraremos los paréntesis al final de nuestras declaraciones de variables:
;create a new layer for the image: (theLayer (car (gimp-layer-new theImage "layer 1" theImageWidth theImageHeight RGB-IMAGE 100 LAYER-MODE-NORMAL ) ) ) ) ;end of our local variables
Una vez se termine la capa nueva, se necesita añadirla a la imagen:
(gimp-image-insert-layer theImage theLayer 0 0)
Ahora, por diversión, se verán los frutos de su labor hasta este punto, y se añadirá esta línea para mostrar la imagen nueva y vacía:
(gimp-display-new theImage)
Save your work, restart GIMP, run the script and a new image should pop up. It will probably contain garbage (random colors), because we haven't erased it. We'll get to that in a second.
Avancemos, elimine la línea de representación de la imagen (o coméntela con un (;
) como primer carácter de la línea).
Antes de añadir texto a la imagen, necesitamos seleccionar los colores de fondo y frente, para que así aparezca con el color especificado por el usuario. Usaremos las funciones de Gimp para establecer el contexto de primer plano y de fondo:
(gimp-context-set-background '(255 255 255) ) (gimp-context-set-foreground inTextColor)
Con los colores seleccionados correctamente, ahora, limpie la basura actual en la imagen para rellenar el dibujable con el color de fondo:
(gimp-drawable-fill theLayer FILL-BACKGROUND)
Con la imagen limpia, está listo para añadir algún texto:
(set! theText (car (gimp-text-font theImage theLayer 0 0 inText 0 TRUE inFontSize inFont) ) )
Aunque hay una llamada de función larga, es bastante más sencillo si repasa los parámetros mientras mira la entrada de la función en el visor de procedimientos. Básicamente, se crea una nueva capa de texto y se asigna a la variable theText
.
Ahora que tiene el texto, puede coger el ancho y alto y redimensionar la imagen y la capa de la imagen al tamaño del texto:
(set! theImageWidth (car (gimp-drawable-get-width theText) ) ) (set! theImageHeight (car (gimp-drawable-get-height theText) ) ) (gimp-image-resize theImage theImageWidth theImageHeight 0 0) (gimp-layer-resize theLayer theImageWidth theImageHeight 0 0)
Si es como yo, se preguntará qué es un dibujable comparado con una capa. La diferencia entre los dos es que un dibujable es algo en lo que puedes dibujar, incluidas capas, pero también canales, máscaras de capa, la selección, etc; una capa es una versión más especifica de un dibujable. En la mayoría de los casos, la distinción no es importante.
Con la imagen lista, puede volver añadir su línea de representación:
(gimp-display-new theImage)
Save your work, restart GIMP and give your first script a run!
If you try to close the image created without first saving the file, GIMP will ask you if you want to save your work before you close the image. It asks this because the image is marked as dirty, or unsaved. In the case of our script, this is a nuisance for the times when we simply give it a test run and don't add or change anything in the resulting image — that is, our work is easily reproducible in such a simple script, so it makes sense to get rid of this dirty flag.
Para hacer esto, puede limpiar la marca sucia después de mostrar la imagen:
(gimp-image-clean-all theImage)
Esto establece a 0 el contador sucio, haciéndolo aparecer como una imagen “limpia”.
Añadir esta línea o no es cuestión del gusto personal. Úselo en scripts que produzcan nuevas imágenes, donde los resultados son triviales, como en este caso. Si su script es muy complicado, o si trabaja sobre una imagen existente, probablemente no querrá usar esta función.