diff --git a/rsvg-image.c b/rsvg-image.c
index e225a47..dd5c6cc 100644
--- a/rsvg-image.c
+++ b/rsvg-image.c
@@ -47,7 +47,7 @@ rsvg_cairo_surface_new_from_href (RsvgHandle *handle,
     GdkPixbufLoader *loader;
     GdkPixbuf *pixbuf = NULL;
     int res;
-    cairo_surface_t *surface;
+    cairo_surface_t *surface = NULL;
 
     data = _rsvg_handle_acquire_data (handle, href, &mime_type, &data_len, error);
     if (data == NULL)
@@ -55,46 +55,58 @@ rsvg_cairo_surface_new_from_href (RsvgHandle *handle,
 
     if (mime_type) {
         loader = gdk_pixbuf_loader_new_with_mime_type (mime_type, error);
-        g_free (mime_type);
     } else {
         loader = gdk_pixbuf_loader_new ();
     }
 
     if (loader == NULL) {
         g_free (data);
-        return NULL;
+        goto out;
     }
 
     res = gdk_pixbuf_loader_write (loader, data, data_len, error);
-    g_free (data);
 
     if (!res) {
+        g_free (data);
         gdk_pixbuf_loader_close (loader, NULL);
         g_object_unref (loader);
-        return NULL;
+        goto out;
     }
 
     if (!gdk_pixbuf_loader_close (loader, error)) {
+        g_free (data);
         g_object_unref (loader);
-        return NULL;
+        goto out;
     }
 
     pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
 
     if (!pixbuf) {
+        g_free (data);
         g_object_unref (loader);
         g_set_error (error,
                      GDK_PIXBUF_ERROR,
                      GDK_PIXBUF_ERROR_FAILED,
                       _("Failed to load image '%s': reason not known, probably a corrupt image file"),
                       href);
-        return NULL;
+        goto out;
     }
 
     surface = rsvg_cairo_surface_from_pixbuf (pixbuf);
-
+    if (mime_type) {
+        if (cairo_surface_set_mime_data (surface, mime_type, data, data_len, g_free, data)) {
+            surface = rsvg_cairo_surface_from_pixbuf (pixbuf);
+            g_free (data);
+        }
+    } else {
+        g_free (data);
+    }
     g_object_unref (loader);
 
+  out:
+    if (mime_type)
+        g_free (mime_type);
+
     return surface;
 }
 
