Difference between revisions of "BGRABitmap/es"

From Free Pascal wiki
Jump to navigationJump to search
(→‎About: InvalidateBitmap call)
m (Fixed syntax highlighting; deleted category already in page template)
(47 intermediate revisions by 11 users not shown)
Line 1: Line 1:
===About===
+
{{BGRABitmap}}
'''BGRABitmap''' is a set of units designed to handle images with transparency (alpha channel). It allows to perform fast memory image processing and pixel manipulations. The standard version should work on any platform. There is an optimised version for Windows. It is not optimised yet for other systems.
 
  
The main class is ''TRGB32Bitmap'' which is derived from ''TFPCustomImage''. There is also ''TBGRAPtrBitmap'' which allows you to modify some data already allocated as a BGRA image. The BGRA format consists of four bytes for each pixel (blue, green, red and alpha in that order).
+
Ver tambien: [[Developing with Graphics]]
  
There are three basic modes for drawing :
+
===Description===
* Drawing with alpha blending (you can draw a transparent object)
+
'''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.
* Replacing pixels including alpha channel (you can draw a hole in the bitmap)
 
* Drawing an image except transparent pixels (like a simple sprite)
 
  
You can draw using direct drawing functions embedded in the ''TBGRABitmap'' class or you can access a ''Canvas'' property to draw using standard functions. The second option is slower because it can need some transformations of the picture. To specity the opacity of objects drawn with the ''Canvas'' property, you can specify a ''CanvasOpacity'' value.
+
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)
  
Available direct functions for drawing :
+
===Usando BGRABitmap===
* pixels, lines, rectangles
 
* lines with anti-aliasing
 
* round rectangles
 
* text with transparency
 
* flood fill, replace color
 
* loading and saving images
 
* resample, merge images
 
  
To access directly to pixels, use the ''Data'' and ''Scanline'' properties. You need to call ''InvalidateBitmap'' to take changes into account for example if you draw the bitmap on a ''Canvas''. Note that the row order can be reversed according to ''LineOrder'' property.
+
====Tutorial====
 +
 
 +
*[http://www.youtube.com/watch?v=HGYSLgtYx-U Cómo convertir una aplicación de TCanvas a BGRABitmap (inglés)]
 +
*[[BGRABitmap tutorial|Una serie de tutoriales para aprender paso por paso (inglés)]]
 +
*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;
 +
</syntaxhighlight>
 +
 
 +
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 lang="pascal">
 +
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;
 +
</syntaxhighlight>
 +
 
 +
Finalmente a mostrar el mapa de bits:
 +
 
 +
<syntaxhighlight lang="pascal">
 +
procedure TFMain.FormPaint(Sender: TObject);
 +
begin
 +
  bmp.Draw(Canvas, 0, 0, True); // draw the bitmap in opaque mode (faster)
 +
end;
 +
</syntaxhighlight>
 +
 
 +
===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.
 +
 
 +
<syntaxhighlight lang="pascal">
 +
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;
 +
</syntaxhighlight>
 +
 
 +
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 [[Fast direct pixel access|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 ===
 
=== Screenshots ===
 
+
[[Image:Lazpaint_contour.png]]
 +
[[Image:Lazpaint curve redim.png]]
 
[[Image:Bgra_wirecube.png]]
 
[[Image:Bgra_wirecube.png]]
 
[[Image:Bgra_chessboard.jpg]]
 
[[Image:Bgra_chessboard.jpg]]
  
===License===
+
===Licence===
GNU General Public License
+
modified LGPL
+
 
===Download and feedback===
+
===Download===
http://consume.o2switch.net/lazarus/
+
Latest version: https://github.com/bgrabitmap/bgrabitmap/releases
 +
 
 +
Sourceforge with [[LazPaint|LazPaint]]: http://sourceforge.net/projects/lazpaint/files/src/
  
===To do===
+
GitHub: https://github.com/bgrabitmap/lazpaint/
* Optimization for other operating systems than Windows
 
  
===Installation===
+
Old link: http://lazarus.johann-elsass.net/
Add BGRABitmap and BGRABitmap types to the '''uses''' clause.
 

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/