Convertire un file immagine SVG in un file immagine di altro formato con le funzioni esterne delle librerie librsvg e libgdk pixbuf

Da Gambas-it.org - Wikipedia.

Utilizzando alcune funzioni esterne delle librerie librsvg e libgdk pixbuf di GNOME è possibile convertire un file immagine SVG in un file immagine di altro formato. Tali formati possibili sono di base "jpeg", "png", "ico" e "bmp", ma possono essere installati altri formati.

In particolare la libreria "librsvg" è utilizzata per effettuare il rendering di immagini di formato SVG, mentre la libreria "libgdk pixbuf" è utilizzata per caricare e gestire immagini.

E' necessario avere installate nel sistema e richiamare in Gambas le librerie dinamiche condivise: "libgdk_pixbuf-2.0" e "librsvg-2.so.2.40.13"


Mostriamo di seguito un esempio, nel quale sarà caricato un file immagine SVG che sarà convertito in formato PNG:

Library "librsvg-2:2.40.13"

' RsvgHandle * rsvg_handle_new_from_file (const gchar *file_name, GError **error)
' Loads the SVG specified by file_name.
Private Extern rsvg_handle_new_from_file(file_name As String, gerror As Pointer) As Pointer

' GdkPixbuf * rsvg_handle_get_pixbuf (RsvgHandle *handle)
' Returns the pixbuf loaded by handle.
Private Extern rsvg_handle_get_pixbuf(handle As Pointer) As Pointer

' gboolean rsvg_handle_close (RsvgHandle *handle, GError **error)
' Closes handle , to indicate that loading the image is complete.
Private Extern rsvg_handle_close(handle As Pointer, gerror As Pointer) As Boolean


Library "libgdk_pixbuf-2.0"

' gboolean gdk_pixbuf_save (GdkPixbuf *pixbuf, const char *filename, const char *type, GError **error, ...)
' Saves pixbuf to a file in format type. By default, "jpeg", "png", "ico" and "bmp" are possible file formats to save in.
Private Extern gdk_pixbuf_save(pixbuf As Pointer, filename As String, type As String, gerror As Pointer, altro As Pointer) As Boolean

' void g_object_unref (gpointer object)
' Decreases the reference count of object.
Private Extern g_object_unref(gobject As Pointer)


Public Sub Main()
 
 Dim rsvg, pbf As Pointer
 Dim bo As Boolean
  
' Carica il file immagine SGV da convertire:
  rsvg = rsvg_handle_new_from_file("/percorso/del/file/immagine.svg", 0)
  
  rsvg_handle_close(rsvg, 0)
  
  pbf = rsvg_handle_get_pixbuf(rsvg)
  
' Converte il file immagine SGV nel nuovo file immagine di formato PNG:
  bo = gdk_pixbuf_save(pbf, "/percorso/del/file/immagine.png", "png", 0, 0)
  If Not bo Then Error.Raise("ERRORE !")
  
  
' In fine libera la memoria occupata dalle due librerie esterne utilizzate:
  g_object_unref(pbf)
  g_object_unref(rsvg)
  
End


Riferimenti