Difference between revisions of "BGRABitmap/es"

From Lazarus wiki
Jump to navigationJump to search
m (Fixed syntax highlighting; deleted category already in page template)
(15 intermediate revisions by 5 users not shown)
Line 1: Line 1:
 
{{BGRABitmap}}
 
{{BGRABitmap}}
  
See also: [[Developing with Graphics]]
+
Ver tambien: [[Developing with Graphics]]
  
 
===Description===
 
===Description===
'''BGRABitmap''' is a set of units designed to modify and create images with transparency (alpha channel). Direct pixel access allows fast image processing. The library has been tested on Windows, Ubuntu and Mac OS X (The last version doesn't work on Mac), with widgetsets win32, gtk1, gtk2 and carbon.
+
'''BGRABitmap''' es un conjunto de unidades diseñado para modificar y crear imagenes con transparencia (canales alfa). El acceso directo a un pixel permite procesar rapidamente una imagen. La libreria a sido probado en Windows, Ubuntu y Mac OS X (La última versión no trabaja en Mac), con win32, gtk1, gtk2 y carbon.
  
The main class is ''TBGRABitmap'', which is derived from ''TFPCustomImage''. There is also ''TBGRAPtrBitmap'' which allows to edit BGRA data that are already allocated. This format consists of 4 bytes for each pixel (blue, green, red and alpha in that order).
+
La clase principal es ''TBGRABitmap'', el cual es derivado de ''TFPCustomImage''. Tambien esta ''TBGRAPtrBitmap'' el cual permite editar datos BGRA que estan actualmente cargados en memoria. Este formato se compone de 4 bytes por cada pixel (azul, verde, rojo y alfa en ese orden)  
  
===Tutorial===
+
===Usando BGRABitmap===
[[BGRABitmap tutorial|Go to the tutorial]].
 
  
There are also examples in testbgrafunc folder of LazPaint archives (see download section).
+
====Tutorial====
  
===Using BGRABitmap===
+
*[http://www.youtube.com/watch?v=HGYSLgtYx-U Cómo convertir una aplicación de TCanvas a BGRABitmap (inglés)]
You must copy BGRABitmap units and link them to your project:
+
*[[BGRABitmap tutorial|Una serie de tutoriales para aprender paso por paso (inglés)]]
<syntaxhighlight>
+
*Ejemplos en [http://lazpaint.svn.sourceforge.net/viewvc/lazpaint/ LazPaint repository].
 +
 
 +
==== Información General ====
 +
 
 +
Muchas funciones de TBGRABitmap tienen nombres largos. Casi todo es accesible como una función o una propiedad del objeto TBGRABitmap. Por ejemplo, puede utilizar CanvasBGRA tener algo similar a TCanvas y Canvas2D para tener características como el [https://developer.mozilla.org/en/HTML:Canvas lienzo (''canvas'') HTML].
 +
 
 +
Algunas caracteristicas especiales requieren el uso de unidades, pero de repente no los necesite. Por ejemplo TBGRAMultishapeFiller que tiene una funcion antialiased de poligonos esta en BGRAPolygon, TBGRATextEffect esta en BGRATextFX, las trasnformaciones 2D estan en BGRATransform, TBGRAScene3D esta en BGRAScene3D. Tenga en cuenta que los nombres de las unidades son adecuados para que se pueda pueda encontrar lo que se necesita.
 +
 
 +
Double-buffering en realidad no forma parte de BGRABitmap, porque este trata más acerca de como manipular los formularios. Para hacer un double-buffering, se puede usar TBGRAVirtualScreen el esta en el paquete [[BGRAControls]].
 +
 
 +
Aprte de esto, el double-buffering que esta en BGRABitmap trabaja igual que un double-buffering. Se necesita tener un mapa de bits para almacenar el dibujo, para después mostrarlo con un simple instrucción. Si necesita usar capas, BGRALayers proporciona TBGRALayeredBitmap.
 +
 
 +
====Ejemplo Simple ====
 +
 
 +
Se debe copiar la unidad BGRABitmap y enlazarlo a tu projecto:
 +
 
 +
<syntaxhighlight lang="pascal">
 
Uses Classes, SysUtils, BGRABitmap, BGRABitmapTypes;
 
Uses Classes, SysUtils, BGRABitmap, BGRABitmapTypes;
 
</syntaxhighlight>
 
</syntaxhighlight>
  
The unit BGRABitmapTypes contains all necessary definitions, but one can declare only BGRABitmap in order to load and show a bitmap. Then, the first step is to create a TBGRABitmap object:
+
La unidad BGRABitmapTypes contiene todas las definiciones necesarias, pero se debe declarar una variable de tipo BGRABitmap para cargar y mostrar un mapa de bits. Entonces, el primer paso es crear un objeto TBGRABitmap:  
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang="pascal">
 
var bmp: TBGRABitmap;
 
var bmp: TBGRABitmap;
 
begin
 
begin
Line 30: Line 46:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Finally to show the bitmap:
+
Finalmente a mostrar el mapa de bits:
<syntaxhighlight>
+
 
 +
<syntaxhighlight lang="pascal">
 
procedure TFMain.FormPaint(Sender: TObject);
 
procedure TFMain.FormPaint(Sender: TObject);
 
begin
 
begin
Line 38: Line 55:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===Notions===
+
===Nociones===
  
Pixels in a bitmap with transparency are stored with 4 values, here 4 bytes in the order Blue, Green, Red, Alpha. The last channel defines the level of opacity (0 signifies transparent, 255 signifies opaque), other channels define color and luminosity.
+
Los pixels en un mapa de bits con transparencia son guardados con 4 valores, con 4 bytes en el siguiente orden azul, verde, rojo y alfa. El último canal define el nivel de opacidad (0 significa trasnparente, 255 significa opaco), los otros canales definen el color.
  
There are basically two drawing modes. The first consists in replacing the content of the pixel information, the second consists in blending the pixel already here with the new one, which is called alpha blending.
+
Existen basicamente dos modos de pintado. El primero consiste en reemplazar la informacion correspondiente del pixel a dibujar, el segundo consiste en mezclar el pixel existente con el nuevo, el cual es llamada "alpha blending"
  
BGRABitmap functions propose 4 modes:
+
Las funciones BGRABitmap proponen 4 modos:
* dmSet : replaces the four bytes of the drawn pixel, transparency not handled
+
* dmSet : reemplaza los cuatro bytes del pixel a dibujar, no manipula la transparencia.
* dmDrawWithTransparency : draws with alphablending and with gamma correction (see below)
+
* dmDrawWithTransparency : dibuja con "alpha blending" y con correción de gamma (ver abajo).
* dmFastBlend or dmLinearBlend : draws with alphablending but without gamma correction (faster but entails color distortions with low intensities).
+
* dmFastBlend or dmLinearBlend : dibuja con "alpha blending" pero sin correción de gamma. (rápido pero produce distorsiones de color con intensidades bajas).
* dmXor : apply Xor to each component including alpha (if you want to invert color but keep alpha, use BGRA(255,255,255,0) )
+
* dmXor : aplica Xor para cada componente, incluido el alfa (si desea invertir el color y mantener el componente alfa, utilizar BGRA (255,255,255,0))
  
===Integrated drawing functions===
+
===Funciones integradas de dibujo===
  
* draw/erase pixels
+
* dibuja/borra pixels
* draw a line with or without antialiasing
+
* dibuja una linea con o sin antialiasing
* floating point coordinates
+
* coordenadas de punto flotante
* floating point pen width
+
* ancho de lapiz con punto flotante
* rectangle (frame or fill)
+
* rectangulo (marco o relleno)
* ellipse and polygons with antialiasing
+
* Elipses y poligonos con antialiasing
* spline computation (rounded curve)
+
* cálcula spline (curvas suaves)
* simple fill (Floodfill) or progressive fill
+
* relleno simple (Floodfill) o relleno progresivo
* color gradient rendering (linéaire, radial...)
+
* representacion de colores degradados (lineal, radial, ...)
* round rectangles
+
* rectangulos redondeados
* texts with transparency
+
* textos con transparencia
  
===Drawing with the Canvas===
+
===Dibujando con Canvas===
  
It is possible to draw with a ''Canvas'' object, with usual functions but without antialiasing. Opacity of drawing is defined by the ''CanvasOpacity'' property. This way is slower because it needs image transformations.
+
Es posible dibujar con un objeto ''Canvas'', con las funciones usuales pero sin antialiasing. La opacidad de los dibujado es definido por la propiedad ''CanvasOpacity''. Este suele ser lento porque necesita de los algoritmos de transformacion de imagen. Si su proyecto lo permite, es mejor utilizar CanvasBGRA en su lugar, el cual permite usar transparencia y anti-aliasing con los mismos nombres de las funciones que tiene TCanvas.
  
 
===Direct access to pixels===
 
===Direct access to pixels===
Line 72: Line 89:
 
To access pixels, there are two properties, ''Data'' and ''Scanline''. The first gives a pointer to the first pixel of the image, and the second gives a pointer to the first pixel of a given line.
 
To access pixels, there are two properties, ''Data'' and ''Scanline''. The first gives a pointer to the first pixel of the image, and the second gives a pointer to the first pixel of a given line.
  
<syntaxhighlight>
+
<syntaxhighlight lang="pascal">
 
var  
 
var  
 
   bmp: TBGRABitmap;
 
   bmp: TBGRABitmap;
Line 98: Line 115:
 
=== Image manipulation ===
 
=== Image manipulation ===
  
Available filters:
+
Available filters (prefixed with Filter) :
  
 
* Radial blur : non directional blur
 
* Radial blur : non directional blur
 
* Motion blur : directional blur
 
* Motion blur : directional blur
 
* Custom blur : blur according to a mask
 
* Custom blur : blur according to a mask
 +
 
* Median : computes the median of colors around each pixel, which softens corners
 
* Median : computes the median of colors around each pixel, which softens corners
 +
* Pixelate : simplifies the image with rectangles of the same color
 
* Smooth : soften whole image, complementary to Sharpen
 
* Smooth : soften whole image, complementary to Sharpen
 
* Sharpen : makes contours more accute, complementary to Smooth
 
* Sharpen : makes contours more accute, complementary to Smooth
 +
 
* Contour : draws contours on a white background (like a pencil drawing)
 
* Contour : draws contours on a white background (like a pencil drawing)
 
* Emboss : draws contours with shadow
 
* Emboss : draws contours with shadow
 
* EmbossHighlight : draws contours of a selection defined with grayscale
 
* EmbossHighlight : draws contours of a selection defined with grayscale
 +
 
* Grayscale : converts colors to grayscale with gamma correction
 
* Grayscale : converts colors to grayscale with gamma correction
 
* Normalize : uses whole range of color luminosity  
 
* Normalize : uses whole range of color luminosity  
 +
 
* Rotate : rotation of the image around a point
 
* Rotate : rotation of the image around a point
 +
* Sphere : distorts the image to make it look like projected on a sphere
 +
* Twirl : distorts the image with a twirl effect
 +
* Cylinder : distorts the image to make it look like projected on a cylinder
 +
* Plane : computes a high precision projection on a horizontal plane. This is quite slow.
 
* SmartZoom3 : resizes the image x3 and detects borders, to have a useful zoom with ancient games sprites
 
* SmartZoom3 : resizes the image x3 and detects borders, to have a useful zoom with ancient games sprites
 +
 +
Some functions are not prefixed with Filter, because they do not return a newly allocated image. They modify the image in-place :
 +
* VerticalFlip : flips the image vertically
 +
* HoriztonalFlip : flips the image horizontally
 +
* Negative : inverse of colors
 +
* LinearNegative : inverse without gamma correction
 +
* SwapRedBlue : swap red and blue channels (to convert between BGRA and RGBA)
 +
* ConvertToLinearRGB : to convert from sRGB to RGB. Note the format used by BGRABitmap is sRGB when using
 +
dmDrawWithTransparency and RGB when using dmLinearBlend.
 +
* ConvertFromLinearRGB : convert from RGB to sRGB.
  
 
=== Images combination ===
 
=== Images combination ===
Line 132: Line 168:
 
*Darken : keeps the darkest color values
 
*Darken : keeps the darkest color values
 
*Xor : exclusive or of color values
 
*Xor : exclusive or of color values
 +
 +
These modes can be used in TBGRALayeredBitmap, which makes it easier because BlendImage only provides the basic blending operations.
  
 
=== Screenshots ===
 
=== Screenshots ===
Line 143: Line 181:
  
 
===Download===
 
===Download===
Sourceforge with [[LazPaint|LazPaint]] and BGRABitmap : https://sourceforge.net/projects/lazpaint/files/
+
Latest version: https://github.com/bgrabitmap/bgrabitmap/releases
  
Old link : http://consume.o2switch.net/lazarus/
+
Sourceforge with [[LazPaint|LazPaint]]: http://sourceforge.net/projects/lazpaint/files/src/
  
===Installation===
+
GitHub: https://github.com/bgrabitmap/lazpaint/
Add BGRABitmap and BGRABitmapTypes to the '''uses''' clause.
 
  
[[Category:Components]]
+
Old link: http://lazarus.johann-elsass.net/
[[Category:Graphics]]
 

Revision as of 06:21, 10 February 2020

Deutsch (de) English (en) español (es) français (fr) русский (ru) 中文(中国大陆)‎ (zh_CN)

bgrabitmap logo.jpg

Ver tambien: Developing with Graphics

Description

BGRABitmap es un conjunto de unidades diseñado para modificar y crear imagenes con transparencia (canales alfa). El acceso directo a un pixel permite procesar rapidamente una imagen. La libreria a sido probado en Windows, Ubuntu y Mac OS X (La última versión no trabaja en Mac), con win32, gtk1, gtk2 y carbon.

La clase principal es TBGRABitmap, el cual es derivado de TFPCustomImage. Tambien esta TBGRAPtrBitmap el cual permite editar datos BGRA que estan actualmente cargados en memoria. Este formato se compone de 4 bytes por cada pixel (azul, verde, rojo y alfa en ese orden)

Usando BGRABitmap

Tutorial

Información General

Muchas funciones de TBGRABitmap tienen nombres largos. Casi todo es accesible como una función o una propiedad del objeto TBGRABitmap. Por ejemplo, puede utilizar CanvasBGRA tener algo similar a TCanvas y Canvas2D para tener características como el lienzo (canvas) HTML.

Algunas caracteristicas especiales requieren el uso de unidades, pero de repente no los necesite. Por ejemplo TBGRAMultishapeFiller que tiene una funcion antialiased de poligonos esta en BGRAPolygon, TBGRATextEffect esta en BGRATextFX, las trasnformaciones 2D estan en BGRATransform, TBGRAScene3D esta en BGRAScene3D. Tenga en cuenta que los nombres de las unidades son adecuados para que se pueda pueda encontrar lo que se necesita.

Double-buffering en realidad no forma parte de BGRABitmap, porque este trata más acerca de como manipular los formularios. Para hacer un double-buffering, se puede usar TBGRAVirtualScreen el esta en el paquete BGRAControls.

Aprte de esto, el double-buffering que esta en BGRABitmap trabaja igual que un double-buffering. Se necesita tener un mapa de bits para almacenar el dibujo, para después mostrarlo con un simple instrucción. Si necesita usar capas, BGRALayers proporciona TBGRALayeredBitmap.

Ejemplo Simple

Se debe copiar la unidad BGRABitmap y enlazarlo a tu projecto:

Uses Classes, SysUtils, BGRABitmap, BGRABitmapTypes;

La unidad BGRABitmapTypes contiene todas las definiciones necesarias, pero se debe declarar una variable de tipo BGRABitmap para cargar y mostrar un mapa de bits. Entonces, el primer paso es crear un objeto TBGRABitmap:

var bmp: TBGRABitmap;
begin
  bmp := TBGRABitmap.Create(100,100,BGRABlack); //creates a 100x100 pixels image with black background

  bmp.FillRect(20,20,60,60,BGRAWhite, dmSet); //draws a white square without transparency
  bmp.FillRect(40,40,80,80,BGRA(0,0,255,128), dmDrawWithTransparency); //draws a transparent blue square
end;

Finalmente a mostrar el mapa de bits:

procedure TFMain.FormPaint(Sender: TObject);
begin
  bmp.Draw(Canvas, 0, 0, True); // draw the bitmap in opaque mode (faster)
end;

Nociones

Los pixels en un mapa de bits con transparencia son guardados con 4 valores, con 4 bytes en el siguiente orden azul, verde, rojo y alfa. El último canal define el nivel de opacidad (0 significa trasnparente, 255 significa opaco), los otros canales definen el color.

Existen basicamente dos modos de pintado. El primero consiste en reemplazar la informacion correspondiente del pixel a dibujar, el segundo consiste en mezclar el pixel existente con el nuevo, el cual es llamada "alpha blending"

Las funciones BGRABitmap proponen 4 modos:

  • dmSet : reemplaza los cuatro bytes del pixel a dibujar, no manipula la transparencia.
  • dmDrawWithTransparency : dibuja con "alpha blending" y con correción de gamma (ver abajo).
  • dmFastBlend or dmLinearBlend : dibuja con "alpha blending" pero sin correción de gamma. (rápido pero produce distorsiones de color con intensidades bajas).
  • dmXor : aplica Xor para cada componente, incluido el alfa (si desea invertir el color y mantener el componente alfa, utilizar BGRA (255,255,255,0))

Funciones integradas de dibujo

  • dibuja/borra pixels
  • dibuja una linea con o sin antialiasing
  • coordenadas de punto flotante
  • ancho de lapiz con punto flotante
  • rectangulo (marco o relleno)
  • Elipses y poligonos con antialiasing
  • cálcula spline (curvas suaves)
  • relleno simple (Floodfill) o relleno progresivo
  • representacion de colores degradados (lineal, radial, ...)
  • rectangulos redondeados
  • textos con transparencia

Dibujando con Canvas

Es posible dibujar con un objeto Canvas, con las funciones usuales pero sin antialiasing. La opacidad de los dibujado es definido por la propiedad CanvasOpacity. Este suele ser lento porque necesita de los algoritmos de transformacion de imagen. Si su proyecto lo permite, es mejor utilizar CanvasBGRA en su lugar, el cual permite usar transparencia y anti-aliasing con los mismos nombres de las funciones que tiene TCanvas.

Direct access to pixels

To access pixels, there are two properties, Data and Scanline. The first gives a pointer to the first pixel of the image, and the second gives a pointer to the first pixel of a given line.

var 
   bmp: TBGRABitmap;
   p: PBGRAPixel;
   n: integer;

begin
     bmp := TBGRABitmap.Create('image.png');
     p := bmp.Data;
     for n := bmp.NbPixels-1 downto 0 do
     begin
          p^.red := not p^.red;  //invert red canal
          inc(p);
     end;
     bmp.InvalidateBitmap;  //note that we have accessed directly to pixels
     bmp.Draw(Canvas,0,0,True);
     bmp.Free;
end;

It is necessary to call the function InvalidateBitmap to rebuild the image in a next call to Draw' for example. Notice that the line order can be reverse, depending on the LineOrder property.

See also the comparison between direct pixel access methods.

Image manipulation

Available filters (prefixed with Filter) :

  • Radial blur : non directional blur
  • Motion blur : directional blur
  • Custom blur : blur according to a mask
  • Median : computes the median of colors around each pixel, which softens corners
  • Pixelate : simplifies the image with rectangles of the same color
  • Smooth : soften whole image, complementary to Sharpen
  • Sharpen : makes contours more accute, complementary to Smooth
  • Contour : draws contours on a white background (like a pencil drawing)
  • Emboss : draws contours with shadow
  • EmbossHighlight : draws contours of a selection defined with grayscale
  • Grayscale : converts colors to grayscale with gamma correction
  • Normalize : uses whole range of color luminosity
  • Rotate : rotation of the image around a point
  • Sphere : distorts the image to make it look like projected on a sphere
  • Twirl : distorts the image with a twirl effect
  • Cylinder : distorts the image to make it look like projected on a cylinder
  • Plane : computes a high precision projection on a horizontal plane. This is quite slow.
  • SmartZoom3 : resizes the image x3 and detects borders, to have a useful zoom with ancient games sprites

Some functions are not prefixed with Filter, because they do not return a newly allocated image. They modify the image in-place :

  • VerticalFlip : flips the image vertically
  • HoriztonalFlip : flips the image horizontally
  • Negative : inverse of colors
  • LinearNegative : inverse without gamma correction
  • SwapRedBlue : swap red and blue channels (to convert between BGRA and RGBA)
  • ConvertToLinearRGB : to convert from sRGB to RGB. Note the format used by BGRABitmap is sRGB when using

dmDrawWithTransparency and RGB when using dmLinearBlend.

  • ConvertFromLinearRGB : convert from RGB to sRGB.

Images combination

PutImage is the basic image drawing function and BlendImage allows to combine images, like layers of image editing softwares. Available modes are the following:

  • LinearBlend : simple superimposition without gamma correction (equivalent to dmFastBlend)
  • Transparent : superimposition with gamma correction
  • Multiply : multiplication of color values (with gamma correction)
  • LinearMultiply : multiplication of color values (without gamma correction)
  • Additive : addition of color values (with gamma correction)
  • LinearAdd : addition of color values (without gamma correction)
  • Difference : difference of color values (with gamma correction)
  • LinearDifference : difference of color values (without gamma correction)
  • Negation : makes common colors disappear (with gamma correction)
  • LinearNegation : makes common colors disappear (without gamma correction)
  • Reflect, Glow : for light effects
  • ColorBurn, ColorDodge, Overlay, Screen : misc. filters
  • Lighten : keeps the lightest color values
  • Darken : keeps the darkest color values
  • Xor : exclusive or of color values

These modes can be used in TBGRALayeredBitmap, which makes it easier because BlendImage only provides the basic blending operations.

Screenshots

Lazpaint contour.png Lazpaint curve redim.png Bgra wirecube.png Bgra chessboard.jpg

Licence

modified LGPL

Download

Latest version: https://github.com/bgrabitmap/bgrabitmap/releases

Sourceforge with LazPaint: http://sourceforge.net/projects/lazpaint/files/src/

GitHub: https://github.com/bgrabitmap/lazpaint/

Old link: http://lazarus.johann-elsass.net/