svg.scm 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2016, 2017, 2018 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2015 Andy Wingo <wingo@igalia.com>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (gnu build svg)
  20. #:use-module (rsvg)
  21. #:use-module (cairo)
  22. #:use-module (srfi srfi-11)
  23. #:export (svg->png))
  24. (define* (downscaled-surface surface
  25. #:key
  26. source-width source-height
  27. width height)
  28. "Return a new rendering context where SURFACE is scaled to WIDTH x HEIGHT."
  29. (let ((cr (cairo-create (cairo-image-surface-create 'argb32
  30. width height))))
  31. (cairo-scale cr (/ width source-width) (/ height source-height))
  32. (cairo-set-source-surface cr surface 0 0)
  33. (cairo-pattern-set-filter (cairo-get-source cr) 'best)
  34. (cairo-rectangle cr 0 0 source-width source-height)
  35. (cairo-fill cr)
  36. cr))
  37. (define* (svg->png in-svg out-png
  38. #:key width height)
  39. "Render the file at IN-SVG as a PNG file in OUT-PNG. When WIDTH and HEIGHT
  40. are provided, use them as the dimensions of OUT-PNG; otherwise preserve the
  41. dimensions of IN-SVG."
  42. (define svg
  43. (rsvg-handle-new-from-file in-svg))
  44. (let-values (((origin-width origin-height em ex)
  45. (rsvg-handle-get-dimensions svg)))
  46. (let* ((surf (cairo-image-surface-create 'argb32
  47. origin-width origin-height))
  48. (cr (cairo-create surf)))
  49. (rsvg-handle-render-cairo svg cr)
  50. (cairo-surface-flush surf)
  51. (let ((cr (if (and width height
  52. (not (= width origin-width))
  53. (not (= height origin-height)))
  54. (downscaled-surface surf
  55. #:source-width origin-width
  56. #:source-height origin-height
  57. #:width width
  58. #:height height)
  59. cr)))
  60. (cairo-surface-write-to-png (cairo-get-target cr) out-png)))))
  61. ;;; svg.scm ends here