svg.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import re
  2. def translate_color(svg, pfrom, pto):
  3. """
  4. Translates colours from a source file's original colours into new colours.
  5. """
  6. res, _ = _translate_color(svg, pfrom, pto)
  7. return res
  8. def translated_colors(svg, pfrom, pto):
  9. """
  10. Return a dictionary of (entry: to_colour) for the colours that were
  11. translated in svg
  12. """
  13. _, changed = _translate_color(svg, pfrom, pto)
  14. return changed
  15. def _translate_color(svg, pfrom, pto):
  16. """
  17. Translates colours on the svg file from "pfrom" to "pto", reporting also
  18. which colours changed.
  19. """
  20. # looks for incidences of one colour, compares it and replaces it.
  21. res = svg
  22. changed = {}
  23. for centry, ccol in pfrom.items():
  24. cr = ccol + ';'
  25. cro = pto.get(centry)
  26. if not cro:
  27. continue
  28. cro += ';'
  29. res, count = re.subn(cr, cro, res, flags=re.IGNORECASE)
  30. if (cr[1], cr[3], cr[5]) == (cr[2], cr[4], cr[6]):
  31. cr = cr[0] + cr[1] + cr[3] + cr[5] + ';'
  32. res, count2 = re.sub(cr, cro, res, flags=re.IGNORECASE)
  33. count += count2
  34. # Record changes
  35. if count > 0:
  36. changed[centry] = cro
  37. return (res, changed)
  38. def add_license(svg, license_data):
  39. """
  40. Adds licensing metadata to an SVG.
  41. """
  42. svgidx = svg.index('<svg')
  43. insidx = svg.index('>', svgidx) + 1
  44. metastr = '\n<metadata>\n' + license_data + '</metadata>\n'
  45. return svg[:insidx] + metastr + svg[insidx:]
  46. def get_viewbox_size(svg):
  47. """
  48. Returns the size of an SVG's viewbox (as a tuple containing width and height).
  49. """
  50. try:
  51. x1, y1, x2, y2 = list(map(
  52. int, svg[svg.index('viewBox'):].split('"', 2)[1].split()))
  53. return x2 - x1, y2 - y1
  54. except Exception:
  55. raise ValueError('Could not detect image size')