Creare un file immagine PNG trasparente con le funzioni esterne del API di Cairo

Da Gambas-it.org - Wikipedia.

Con la libreria Cairo è possibile, fra l'altro, creare un file immagine trasparente di tipo PNG (ma anche SVG, PDF e Post-Script).

Per fare ciò, si dovranno utilizzare alcune funzioni esterne della libreria (nella sua attuale versione): libcairo.so.2.11301.0


Mostriamo di seguito un semplice esempio, nel quale verrà creato un file immagine trasparente in formato PNG:

Library "libcairo:2.11301.0"

Private Const CAIRO_FORMAT_ARGB32 As Integer = 0

' cairo_surface_t * cairo_image_surface_create(cairo_format_t formatI, int width, int height)
' Creates an image surface of the specified format and dimensions.
Private Extern cairo_image_surface_create(formatI As Integer, width As Integer, height As Integer) As Pointer
 
' cairo_status_t cairo_surface_write_to_png(cairo_surface_t *surface, const char *filename)
' Writes the contents of surface to a new file filename as a PNG image.
Private Extern cairo_surface_write_to_png(cairo_surface As Pointer, filename As String) As Integer

' cairo_format_t cairo_image_surface_get_format(cairo_surface_t *surface)
' Get the format of the surface.
Private Extern cairo_image_surface_get_format(cairo_surface As Pointer) As Integer

' int cairo_image_surface_get_width(cairo_surface_t *surface)
' Get the width of the image surface in pixels.
Private Extern cairo_image_surface_get_width(cairo_surface As Pointer) As Integer

' int cairo_image_surface_get_height(cairo_surface_t *surface)
' Get the height of the image surface in pixels.
Private Extern cairo_image_surface_get_height(cairo_surface As Pointer) As Integer

' void cairo_destroy(cairo_t *cr)
' Decreases the reference count on cr by one.
Private Extern cairo_destroy(cr As Pointer)

' void cairo_surface_destroy(cairo_surface_t *surface)
' Decreases the reference count on surface by one.
Private Extern cairo_surface_destroy(cairo_surface As Pointer)


Public Sub Main()

 Dim surface As Pointer
 Dim err As Byte
 Dim percorsoFile As String = "/tmp/trasparente_Cairo.png"

' Crea la superficie dell'immagine (in questo caso trasparente):
  surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 400, 200)
  
  err = cairo_surface_write_to_png(surface, percorsoFile)
  If err > 0 Then Error.Raise("Errore nella creazione del file immagine .png !")

' Mostra alcune caratteristiche generali sull'immagine creata:
  Print "Larghezza: ", Null; cairo_image_surface_get_width(surface); " pixel"
  Print "Altezza: ", Null; cairo_image_surface_get_height(surface); " pixel"
  If cairo_image_surface_get_format(surface) = CAIRO_FORMAT_ARGB32 Then Print "Formato: ", Null; "RGBA (32 bit)"


' Va in chiusura:
  cairo_destroy(cairo)
  cairo_surface_destroy(surface)

End



Riferimenti