GimpGradientFile.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #
  2. # Python Imaging Library
  3. # $Id$
  4. #
  5. # stuff to read (and render) GIMP gradient files
  6. #
  7. # History:
  8. # 97-08-23 fl Created
  9. #
  10. # Copyright (c) Secret Labs AB 1997.
  11. # Copyright (c) Fredrik Lundh 1997.
  12. #
  13. # See the README file for information on usage and redistribution.
  14. #
  15. """
  16. Stuff to translate curve segments to palette values (derived from
  17. the corresponding code in GIMP, written by Federico Mena Quintero.
  18. See the GIMP distribution for more information.)
  19. """
  20. from __future__ import annotations
  21. __lazy_modules__ = {"PIL._binary", "math"}
  22. from math import log, pi, sin, sqrt
  23. from ._binary import o8
  24. TYPE_CHECKING = False
  25. if TYPE_CHECKING:
  26. from collections.abc import Callable
  27. from typing import IO
  28. EPSILON = 1e-10
  29. """""" # Enable auto-doc for data member
  30. def linear(middle: float, pos: float) -> float:
  31. if pos <= middle:
  32. if middle < EPSILON:
  33. return 0.0
  34. else:
  35. return 0.5 * pos / middle
  36. else:
  37. pos = pos - middle
  38. middle = 1.0 - middle
  39. if middle < EPSILON:
  40. return 1.0
  41. else:
  42. return 0.5 + 0.5 * pos / middle
  43. def curved(middle: float, pos: float) -> float:
  44. return pos ** (log(0.5) / log(max(middle, EPSILON)))
  45. def sine(middle: float, pos: float) -> float:
  46. return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0
  47. def sphere_increasing(middle: float, pos: float) -> float:
  48. return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)
  49. def sphere_decreasing(middle: float, pos: float) -> float:
  50. return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)
  51. SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
  52. """""" # Enable auto-doc for data member
  53. class GradientFile:
  54. gradient: (
  55. list[
  56. tuple[
  57. float,
  58. float,
  59. float,
  60. list[float],
  61. list[float],
  62. Callable[[float, float], float],
  63. ]
  64. ]
  65. | None
  66. ) = None
  67. def getpalette(self, entries: int = 256) -> tuple[bytes, str]:
  68. assert self.gradient is not None
  69. palette = []
  70. ix = 0
  71. x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
  72. for i in range(entries):
  73. x = i / (entries - 1)
  74. while x1 < x:
  75. ix += 1
  76. x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]
  77. w = x1 - x0
  78. if w < EPSILON:
  79. scale = segment(0.5, 0.5)
  80. else:
  81. scale = segment((xm - x0) / w, (x - x0) / w)
  82. # expand to RGBA
  83. r = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))
  84. g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))
  85. b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))
  86. a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))
  87. # add to palette
  88. palette.append(r + g + b + a)
  89. return b"".join(palette), "RGBA"
  90. class GimpGradientFile(GradientFile):
  91. """File handler for GIMP's gradient format."""
  92. def __init__(self, fp: IO[bytes]) -> None:
  93. if not fp.readline().startswith(b"GIMP Gradient"):
  94. msg = "not a GIMP gradient file"
  95. raise SyntaxError(msg)
  96. line = fp.readline()
  97. # GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files do
  98. if line.startswith(b"Name: "):
  99. line = fp.readline().strip()
  100. count = int(line)
  101. self.gradient = []
  102. for i in range(count):
  103. s = fp.readline().split()
  104. w = [float(x) for x in s[:11]]
  105. x0, x1 = w[0], w[2]
  106. xm = w[1]
  107. rgb0 = w[3:7]
  108. rgb1 = w[7:11]
  109. segment = SEGMENTS[int(s[11])]
  110. cspace = int(s[12])
  111. if cspace != 0:
  112. msg = "cannot handle HSV colour space"
  113. raise OSError(msg)
  114. self.gradient.append((x0, x1, xm, rgb0, rgb1, segment))