BGRABitmap/es

From Free Pascal wiki
Revision as of 20:37, 19 July 2015 by 007 (talk | contribs) (→‎Download)
Jump to navigationJump to search

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

Most functions of TBGRABitmap. They have long names for this purpose. Almost everything is accessible as a function or using a property of the TBGRABitmap object. Por ejemplo, puede utilizar CanvasBGRA tener algo similar a TCanvas y Canvas2D para tener características como el [tela https://developer.mozilla.org/en/HTML:Canvas HTML].

Algunas caracteristicas especiales requieren el uso de unidades, pero derepente 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

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

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

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

If you did not find the information you are looking for or have a suggestion, you can send feedback here.