ImageCms.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. # The Python Imaging Library.
  2. # $Id$
  3. # Optional color management support, based on Kevin Cazabon's PyCMS
  4. # library.
  5. # Originally released under LGPL. Graciously donated to PIL in
  6. # March 2009, for distribution under the standard PIL license
  7. # History:
  8. # 2009-03-08 fl Added to PIL.
  9. # Copyright (C) 2002-2003 Kevin Cazabon
  10. # Copyright (c) 2009 by Fredrik Lundh
  11. # Copyright (c) 2013 by Eric Soroos
  12. # See the README file for information on usage and redistribution. See
  13. # below for the original description.
  14. from __future__ import annotations
  15. import operator
  16. import sys
  17. from enum import IntEnum, IntFlag
  18. from functools import reduce
  19. from . import Image
  20. TYPE_CHECKING = False
  21. if TYPE_CHECKING:
  22. from typing import Literal, SupportsFloat, SupportsInt
  23. from ._typing import SupportsRead
  24. try:
  25. from . import _imagingcms as core
  26. except ImportError as ex:
  27. # Allow error import for doc purposes, but error out when accessing
  28. # anything in core.
  29. from ._util import DeferredError
  30. core = DeferredError.new(ex)
  31. _DESCRIPTION = """
  32. pyCMS
  33. a Python / PIL interface to the littleCMS ICC Color Management System
  34. Copyright (C) 2002-2003 Kevin Cazabon
  35. kevin@cazabon.com
  36. https://www.cazabon.com
  37. pyCMS home page: https://www.cazabon.com/pyCMS
  38. littleCMS home page: https://www.littlecms.com
  39. (littleCMS is Copyright (C) 1998-2001 Marti Maria)
  40. Originally released under LGPL. Graciously donated to PIL in
  41. March 2009, for distribution under the standard PIL license
  42. The pyCMS.py module provides a "clean" interface between Python/PIL and
  43. pyCMSdll, taking care of some of the more complex handling of the direct
  44. pyCMSdll functions, as well as error-checking and making sure that all
  45. relevant data is kept together.
  46. While it is possible to call pyCMSdll functions directly, it's not highly
  47. recommended.
  48. Version History:
  49. 1.0.0 pil Oct 2013 Port to LCMS 2.
  50. 0.1.0 pil mod March 10, 2009
  51. Renamed display profile to proof profile. The proof
  52. profile is the profile of the device that is being
  53. simulated, not the profile of the device which is
  54. actually used to display/print the final simulation
  55. (that'd be the output profile) - also see LCMSAPI.txt
  56. input colorspace -> using 'renderingIntent' -> proof
  57. colorspace -> using 'proofRenderingIntent' -> output
  58. colorspace
  59. Added LCMS FLAGS support.
  60. Added FLAGS["SOFTPROOFING"] as default flag for
  61. buildProofTransform (otherwise the proof profile/intent
  62. would be ignored).
  63. 0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms
  64. 0.0.2 alpha Jan 6, 2002
  65. Added try/except statements around type() checks of
  66. potential CObjects... Python won't let you use type()
  67. on them, and raises a TypeError (stupid, if you ask
  68. me!)
  69. Added buildProofTransformFromOpenProfiles() function.
  70. Additional fixes in DLL, see DLL code for details.
  71. 0.0.1 alpha first public release, Dec. 26, 2002
  72. Known to-do list with current version (of Python interface, not pyCMSdll):
  73. none
  74. """
  75. _VERSION = "1.0.0 pil"
  76. # --------------------------------------------------------------------.
  77. #
  78. # intent/direction values
  79. class Intent(IntEnum):
  80. PERCEPTUAL = 0
  81. RELATIVE_COLORIMETRIC = 1
  82. SATURATION = 2
  83. ABSOLUTE_COLORIMETRIC = 3
  84. class Direction(IntEnum):
  85. INPUT = 0
  86. OUTPUT = 1
  87. PROOF = 2
  88. #
  89. # flags
  90. class Flags(IntFlag):
  91. """Flags and documentation are taken from ``lcms2.h``."""
  92. NONE = 0
  93. NOCACHE = 0x0040
  94. """Inhibit 1-pixel cache"""
  95. NOOPTIMIZE = 0x0100
  96. """Inhibit optimizations"""
  97. NULLTRANSFORM = 0x0200
  98. """Don't transform anyway"""
  99. GAMUTCHECK = 0x1000
  100. """Out of Gamut alarm"""
  101. SOFTPROOFING = 0x4000
  102. """Do softproofing"""
  103. BLACKPOINTCOMPENSATION = 0x2000
  104. NOWHITEONWHITEFIXUP = 0x0004
  105. """Don't fix scum dot"""
  106. HIGHRESPRECALC = 0x0400
  107. """Use more memory to give better accuracy"""
  108. LOWRESPRECALC = 0x0800
  109. """Use less memory to minimize resources"""
  110. # this should be 8BITS_DEVICELINK, but that is not a valid name in Python:
  111. USE_8BITS_DEVICELINK = 0x0008
  112. """Create 8 bits devicelinks"""
  113. GUESSDEVICECLASS = 0x0020
  114. """Guess device class (for ``transform2devicelink``)"""
  115. KEEP_SEQUENCE = 0x0080
  116. """Keep profile sequence for devicelink creation"""
  117. FORCE_CLUT = 0x0002
  118. """Force CLUT optimization"""
  119. CLUT_POST_LINEARIZATION = 0x0001
  120. """create postlinearization tables if possible"""
  121. CLUT_PRE_LINEARIZATION = 0x0010
  122. """create prelinearization tables if possible"""
  123. NONEGATIVES = 0x8000
  124. """Prevent negative numbers in floating point transforms"""
  125. COPY_ALPHA = 0x04000000
  126. """Alpha channels are copied on ``cmsDoTransform()``"""
  127. NODEFAULTRESOURCEDEF = 0x01000000
  128. _GRIDPOINTS_1 = 1 << 16
  129. _GRIDPOINTS_2 = 2 << 16
  130. _GRIDPOINTS_4 = 4 << 16
  131. _GRIDPOINTS_8 = 8 << 16
  132. _GRIDPOINTS_16 = 16 << 16
  133. _GRIDPOINTS_32 = 32 << 16
  134. _GRIDPOINTS_64 = 64 << 16
  135. _GRIDPOINTS_128 = 128 << 16
  136. @staticmethod
  137. def GRIDPOINTS(n: int) -> Flags:
  138. """
  139. Fine-tune control over number of gridpoints
  140. :param n: :py:class:`int` in range ``0 <= n <= 255``
  141. """
  142. return Flags.NONE | ((n & 0xFF) << 16)
  143. _MAX_FLAG = reduce(operator.or_, Flags)
  144. _FLAGS = {
  145. "MATRIXINPUT": 1,
  146. "MATRIXOUTPUT": 2,
  147. "MATRIXONLY": (1 | 2),
  148. "NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot
  149. # Don't create prelinearization tables on precalculated transforms
  150. # (internal use):
  151. "NOPRELINEARIZATION": 16,
  152. "GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)
  153. "NOTCACHE": 64, # Inhibit 1-pixel cache
  154. "NOTPRECALC": 256,
  155. "NULLTRANSFORM": 512, # Don't transform anyway
  156. "HIGHRESPRECALC": 1024, # Use more memory to give better accuracy
  157. "LOWRESPRECALC": 2048, # Use less memory to minimize resources
  158. "WHITEBLACKCOMPENSATION": 8192,
  159. "BLACKPOINTCOMPENSATION": 8192,
  160. "GAMUTCHECK": 4096, # Out of Gamut alarm
  161. "SOFTPROOFING": 16384, # Do softproofing
  162. "PRESERVEBLACK": 32768, # Black preservation
  163. "NODEFAULTRESOURCEDEF": 16777216, # CRD special
  164. "GRIDPOINTS": lambda n: (n & 0xFF) << 16, # Gridpoints
  165. }
  166. # --------------------------------------------------------------------.
  167. # Experimental PIL-level API
  168. # --------------------------------------------------------------------.
  169. ##
  170. # Profile.
  171. class ImageCmsProfile:
  172. def __init__(self, profile: str | SupportsRead[bytes] | core.CmsProfile) -> None:
  173. """
  174. :param profile: Either a string representing a filename,
  175. a file-like object containing a profile or a
  176. low-level profile object
  177. """
  178. self.filename: str | None = None
  179. if isinstance(profile, str):
  180. if sys.platform == "win32":
  181. profile_bytes_path = profile.encode()
  182. try:
  183. profile_bytes_path.decode("ascii")
  184. except UnicodeDecodeError:
  185. with open(profile, "rb") as f:
  186. self.profile = core.profile_frombytes(f.read())
  187. return
  188. self.filename = profile
  189. self.profile = core.profile_open(profile)
  190. elif hasattr(profile, "read"):
  191. self.profile = core.profile_frombytes(profile.read())
  192. elif isinstance(profile, core.CmsProfile):
  193. self.profile = profile
  194. else:
  195. msg = "Invalid type for Profile" # type: ignore[unreachable]
  196. raise TypeError(msg)
  197. def tobytes(self) -> bytes:
  198. """
  199. Returns the profile in a format suitable for embedding in
  200. saved images.
  201. :returns: a bytes object containing the ICC profile.
  202. """
  203. return core.profile_tobytes(self.profile)
  204. if TYPE_CHECKING:
  205. _CmsProfileCompatible = (
  206. str | SupportsRead[bytes] | core.CmsProfile | ImageCmsProfile
  207. )
  208. class ImageCmsTransform(Image.ImagePointHandler):
  209. """
  210. Transform. This can be used with the procedural API, or with the standard
  211. :py:func:`~PIL.Image.Image.point` method.
  212. Will return the output profile in the ``output.info['icc_profile']``.
  213. """
  214. def __init__(
  215. self,
  216. input: ImageCmsProfile,
  217. output: ImageCmsProfile,
  218. input_mode: str,
  219. output_mode: str,
  220. intent: Intent = Intent.PERCEPTUAL,
  221. proof: ImageCmsProfile | None = None,
  222. proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
  223. flags: Flags = Flags.NONE,
  224. ):
  225. if proof is None:
  226. self.transform = core.buildTransform(
  227. input.profile, output.profile, input_mode, output_mode, intent, flags
  228. )
  229. else:
  230. self.transform = core.buildProofTransform(
  231. input.profile,
  232. output.profile,
  233. proof.profile,
  234. input_mode,
  235. output_mode,
  236. intent,
  237. proof_intent,
  238. flags,
  239. )
  240. # Note: inputMode and outputMode are for pyCMS compatibility only
  241. self.input_mode = self.inputMode = input_mode
  242. self.output_mode = self.outputMode = output_mode
  243. self.output_profile = output
  244. def point(self, im: Image.Image) -> Image.Image:
  245. return self.apply(im)
  246. def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
  247. if imOut is None:
  248. imOut = Image.new(self.output_mode, im.size)
  249. self.transform.apply(im.getim(), imOut.getim())
  250. imOut.info["icc_profile"] = self.output_profile.tobytes()
  251. return imOut
  252. def apply_in_place(self, im: Image.Image) -> Image.Image:
  253. return self.apply(im, im)
  254. def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
  255. """
  256. (experimental) Fetches the profile for the current display device.
  257. :returns: ``None`` if the profile is not known.
  258. """
  259. if sys.platform != "win32":
  260. return None
  261. from . import ImageWin # type: ignore[unused-ignore, unreachable]
  262. if isinstance(handle, ImageWin.HDC):
  263. profile = core.get_display_profile_win32(int(handle), 1)
  264. else:
  265. profile = core.get_display_profile_win32(int(handle or 0))
  266. if profile is None:
  267. return None
  268. return ImageCmsProfile(profile)
  269. # --------------------------------------------------------------------.
  270. # pyCMS compatible layer
  271. # --------------------------------------------------------------------.
  272. class PyCMSError(Exception):
  273. """(pyCMS) Exception class.
  274. This is used for all errors in the pyCMS API."""
  275. pass
  276. def profileToProfile(
  277. im: Image.Image,
  278. inputProfile: _CmsProfileCompatible,
  279. outputProfile: _CmsProfileCompatible,
  280. renderingIntent: Intent = Intent.PERCEPTUAL,
  281. outputMode: str | None = None,
  282. inPlace: bool = False,
  283. flags: Flags = Flags.NONE,
  284. ) -> Image.Image | None:
  285. """
  286. (pyCMS) Applies an ICC transformation to a given image, mapping from
  287. ``inputProfile`` to ``outputProfile``.
  288. If the input or output profiles specified are not valid filenames, a
  289. :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
  290. ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
  291. If an error occurs during application of the profiles,
  292. a :exc:`PyCMSError` will be raised.
  293. If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
  294. a :exc:`PyCMSError` will be raised.
  295. This function applies an ICC transformation to im from ``inputProfile``'s
  296. color space to ``outputProfile``'s color space using the specified rendering
  297. intent to decide how to handle out-of-gamut colors.
  298. ``outputMode`` can be used to specify that a color mode conversion is to
  299. be done using these profiles, but the specified profiles must be able
  300. to handle that mode. I.e., if converting im from RGB to CMYK using
  301. profiles, the input profile must handle RGB data, and the output
  302. profile must handle CMYK data.
  303. :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
  304. or Image.open(...), etc.)
  305. :param inputProfile: String, as a valid filename path to the ICC input
  306. profile you wish to use for this image, or a profile object
  307. :param outputProfile: String, as a valid filename path to the ICC output
  308. profile you wish to use for this image, or a profile object
  309. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  310. wish to use for the transform
  311. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  312. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  313. ImageCms.Intent.SATURATION = 2
  314. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  315. see the pyCMS documentation for details on rendering intents and what
  316. they do.
  317. :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
  318. "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
  319. MUST be the same mode as the input, or omitted completely. If
  320. omitted, the outputMode will be the same as the mode of the input
  321. image (im.mode)
  322. :param inPlace: Boolean. If ``True``, the original image is modified in-place,
  323. and ``None`` is returned. If ``False`` (default), a new
  324. :py:class:`~PIL.Image.Image` object is returned with the transform applied.
  325. :param flags: Integer (0-...) specifying additional flags
  326. :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
  327. the value of ``inPlace``
  328. :exception PyCMSError:
  329. """
  330. if outputMode is None:
  331. outputMode = im.mode
  332. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  333. msg = "renderingIntent must be an integer between 0 and 3"
  334. raise PyCMSError(msg)
  335. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  336. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  337. raise PyCMSError(msg)
  338. try:
  339. if not isinstance(inputProfile, ImageCmsProfile):
  340. inputProfile = ImageCmsProfile(inputProfile)
  341. if not isinstance(outputProfile, ImageCmsProfile):
  342. outputProfile = ImageCmsProfile(outputProfile)
  343. transform = ImageCmsTransform(
  344. inputProfile,
  345. outputProfile,
  346. im.mode,
  347. outputMode,
  348. renderingIntent,
  349. flags=flags,
  350. )
  351. if inPlace:
  352. transform.apply_in_place(im)
  353. imOut = None
  354. else:
  355. imOut = transform.apply(im)
  356. except (OSError, TypeError, ValueError) as v:
  357. raise PyCMSError(v) from v
  358. return imOut
  359. def getOpenProfile(
  360. profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
  361. ) -> ImageCmsProfile:
  362. """
  363. (pyCMS) Opens an ICC profile file.
  364. The PyCMSProfile object can be passed back into pyCMS for use in creating
  365. transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
  366. If ``profileFilename`` is not a valid filename for an ICC profile,
  367. a :exc:`PyCMSError` will be raised.
  368. :param profileFilename: String, as a valid filename path to the ICC profile
  369. you wish to open, or a file-like object.
  370. :returns: A CmsProfile class object.
  371. :exception PyCMSError:
  372. """
  373. try:
  374. return ImageCmsProfile(profileFilename)
  375. except (OSError, TypeError, ValueError) as v:
  376. raise PyCMSError(v) from v
  377. def buildTransform(
  378. inputProfile: _CmsProfileCompatible,
  379. outputProfile: _CmsProfileCompatible,
  380. inMode: str,
  381. outMode: str,
  382. renderingIntent: Intent = Intent.PERCEPTUAL,
  383. flags: Flags = Flags.NONE,
  384. ) -> ImageCmsTransform:
  385. """
  386. (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
  387. ``outputProfile``. Use applyTransform to apply the transform to a given
  388. image.
  389. If the input or output profiles specified are not valid filenames, a
  390. :exc:`PyCMSError` will be raised. If an error occurs during creation
  391. of the transform, a :exc:`PyCMSError` will be raised.
  392. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
  393. (or by pyCMS), a :exc:`PyCMSError` will be raised.
  394. This function builds and returns an ICC transform from the ``inputProfile``
  395. to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
  396. with out-of-gamut colors. It will ONLY work for converting images that
  397. are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
  398. i.e. "RGB", "RGBA", "CMYK", etc.).
  399. Building the transform is a fair part of the overhead in
  400. ImageCms.profileToProfile(), so if you're planning on converting multiple
  401. images using the same input/output settings, this can save you time.
  402. Once you have a transform object, it can be used with
  403. ImageCms.applyProfile() to convert images without the need to re-compute
  404. the lookup table for the transform.
  405. The reason pyCMS returns a class object rather than a handle directly
  406. to the transform is that it needs to keep track of the PIL input/output
  407. modes that the transform is meant for. These attributes are stored in
  408. the ``inMode`` and ``outMode`` attributes of the object (which can be
  409. manually overridden if you really want to, but I don't know of any
  410. time that would be of use, or would even work).
  411. :param inputProfile: String, as a valid filename path to the ICC input
  412. profile you wish to use for this transform, or a profile object
  413. :param outputProfile: String, as a valid filename path to the ICC output
  414. profile you wish to use for this transform, or a profile object
  415. :param inMode: String, as a valid PIL mode that the appropriate profile
  416. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  417. :param outMode: String, as a valid PIL mode that the appropriate profile
  418. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  419. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  420. wish to use for the transform
  421. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  422. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  423. ImageCms.Intent.SATURATION = 2
  424. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  425. see the pyCMS documentation for details on rendering intents and what
  426. they do.
  427. :param flags: Integer (0-...) specifying additional flags
  428. :returns: A CmsTransform class object.
  429. :exception PyCMSError:
  430. """
  431. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  432. msg = "renderingIntent must be an integer between 0 and 3"
  433. raise PyCMSError(msg)
  434. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  435. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  436. raise PyCMSError(msg)
  437. try:
  438. if not isinstance(inputProfile, ImageCmsProfile):
  439. inputProfile = ImageCmsProfile(inputProfile)
  440. if not isinstance(outputProfile, ImageCmsProfile):
  441. outputProfile = ImageCmsProfile(outputProfile)
  442. return ImageCmsTransform(
  443. inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
  444. )
  445. except (OSError, TypeError, ValueError) as v:
  446. raise PyCMSError(v) from v
  447. def buildProofTransform(
  448. inputProfile: _CmsProfileCompatible,
  449. outputProfile: _CmsProfileCompatible,
  450. proofProfile: _CmsProfileCompatible,
  451. inMode: str,
  452. outMode: str,
  453. renderingIntent: Intent = Intent.PERCEPTUAL,
  454. proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
  455. flags: Flags = Flags.SOFTPROOFING,
  456. ) -> ImageCmsTransform:
  457. """
  458. (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
  459. ``outputProfile``, but tries to simulate the result that would be
  460. obtained on the ``proofProfile`` device.
  461. If the input, output, or proof profiles specified are not valid
  462. filenames, a :exc:`PyCMSError` will be raised.
  463. If an error occurs during creation of the transform,
  464. a :exc:`PyCMSError` will be raised.
  465. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
  466. (or by pyCMS), a :exc:`PyCMSError` will be raised.
  467. This function builds and returns an ICC transform from the ``inputProfile``
  468. to the ``outputProfile``, but tries to simulate the result that would be
  469. obtained on the ``proofProfile`` device using ``renderingIntent`` and
  470. ``proofRenderingIntent`` to determine what to do with out-of-gamut
  471. colors. This is known as "soft-proofing". It will ONLY work for
  472. converting images that are in ``inMode`` to images that are in outMode
  473. color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
  474. Usage of the resulting transform object is exactly the same as with
  475. ImageCms.buildTransform().
  476. Proof profiling is generally used when using an output device to get a
  477. good idea of what the final printed/displayed image would look like on
  478. the ``proofProfile`` device when it's quicker and easier to use the
  479. output device for judging color. Generally, this means that the
  480. output device is a monitor, or a dye-sub printer (etc.), and the simulated
  481. device is something more expensive, complicated, or time consuming
  482. (making it difficult to make a real print for color judgement purposes).
  483. Soft-proofing basically functions by adjusting the colors on the
  484. output device to match the colors of the device being simulated. However,
  485. when the simulated device has a much wider gamut than the output
  486. device, you may obtain marginal results.
  487. :param inputProfile: String, as a valid filename path to the ICC input
  488. profile you wish to use for this transform, or a profile object
  489. :param outputProfile: String, as a valid filename path to the ICC output
  490. (monitor, usually) profile you wish to use for this transform, or a
  491. profile object
  492. :param proofProfile: String, as a valid filename path to the ICC proof
  493. profile you wish to use for this transform, or a profile object
  494. :param inMode: String, as a valid PIL mode that the appropriate profile
  495. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  496. :param outMode: String, as a valid PIL mode that the appropriate profile
  497. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  498. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  499. wish to use for the input->proof (simulated) transform
  500. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  501. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  502. ImageCms.Intent.SATURATION = 2
  503. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  504. see the pyCMS documentation for details on rendering intents and what
  505. they do.
  506. :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
  507. you wish to use for proof->output transform
  508. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  509. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  510. ImageCms.Intent.SATURATION = 2
  511. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  512. see the pyCMS documentation for details on rendering intents and what
  513. they do.
  514. :param flags: Integer (0-...) specifying additional flags
  515. :returns: A CmsTransform class object.
  516. :exception PyCMSError:
  517. """
  518. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  519. msg = "renderingIntent must be an integer between 0 and 3"
  520. raise PyCMSError(msg)
  521. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  522. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  523. raise PyCMSError(msg)
  524. try:
  525. if not isinstance(inputProfile, ImageCmsProfile):
  526. inputProfile = ImageCmsProfile(inputProfile)
  527. if not isinstance(outputProfile, ImageCmsProfile):
  528. outputProfile = ImageCmsProfile(outputProfile)
  529. if not isinstance(proofProfile, ImageCmsProfile):
  530. proofProfile = ImageCmsProfile(proofProfile)
  531. return ImageCmsTransform(
  532. inputProfile,
  533. outputProfile,
  534. inMode,
  535. outMode,
  536. renderingIntent,
  537. proofProfile,
  538. proofRenderingIntent,
  539. flags,
  540. )
  541. except (OSError, TypeError, ValueError) as v:
  542. raise PyCMSError(v) from v
  543. buildTransformFromOpenProfiles = buildTransform
  544. buildProofTransformFromOpenProfiles = buildProofTransform
  545. def applyTransform(
  546. im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
  547. ) -> Image.Image | None:
  548. """
  549. (pyCMS) Applies a transform to a given image.
  550. If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
  551. If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
  552. :exc:`PyCMSError` is raised.
  553. If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
  554. supported by pyCMSdll or the profiles you used for the transform, a
  555. :exc:`PyCMSError` is raised.
  556. If an error occurs while the transform is being applied,
  557. a :exc:`PyCMSError` is raised.
  558. This function applies a pre-calculated transform (from
  559. ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
  560. to an image. The transform can be used for multiple images, saving
  561. considerable calculation time if doing the same conversion multiple times.
  562. If you want to modify im in-place instead of receiving a new image as
  563. the return value, set ``inPlace`` to ``True``. This can only be done if
  564. ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
  565. can't change the mode in-place (the buffer sizes for some modes are
  566. different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
  567. object of the same dimensions in mode ``transform.output_mode``.
  568. :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
  569. as the ``input_mode`` supported by the transform.
  570. :param transform: A valid CmsTransform class object
  571. :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
  572. returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
  573. transform applied is returned (and ``im`` is not changed). The default is
  574. ``False``.
  575. :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
  576. depending on the value of ``inPlace``. The profile will be returned in
  577. the image's ``info['icc_profile']``.
  578. :exception PyCMSError:
  579. """
  580. try:
  581. if inPlace:
  582. transform.apply_in_place(im)
  583. imOut = None
  584. else:
  585. imOut = transform.apply(im)
  586. except (TypeError, ValueError) as v:
  587. raise PyCMSError(v) from v
  588. return imOut
  589. def createProfile(
  590. colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
  591. ) -> core.CmsProfile:
  592. """
  593. (pyCMS) Creates a profile.
  594. If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
  595. a :exc:`PyCMSError` is raised.
  596. If using LAB and ``colorTemp`` is not a positive integer,
  597. a :exc:`PyCMSError` is raised.
  598. If an error occurs while creating the profile,
  599. a :exc:`PyCMSError` is raised.
  600. Use this function to create common profiles on-the-fly instead of
  601. having to supply a profile on disk and knowing the path to it. It
  602. returns a normal CmsProfile object that can be passed to
  603. ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
  604. to images.
  605. :param colorSpace: String, the color space of the profile you wish to
  606. create.
  607. Currently only "LAB", "XYZ", and "sRGB" are supported.
  608. :param colorTemp: Positive number for the white point for the profile, in
  609. degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
  610. illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
  611. profiles, and is ignored for XYZ and sRGB.
  612. :returns: A CmsProfile class object
  613. :exception PyCMSError:
  614. """
  615. if colorSpace not in ["LAB", "XYZ", "sRGB"]:
  616. msg = (
  617. f"Color space not supported for on-the-fly profile creation ({colorSpace})"
  618. )
  619. raise PyCMSError(msg)
  620. if colorSpace == "LAB":
  621. try:
  622. colorTemp = float(colorTemp)
  623. except (TypeError, ValueError) as e:
  624. msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
  625. raise PyCMSError(msg) from e
  626. try:
  627. return core.createProfile(colorSpace, colorTemp)
  628. except (TypeError, ValueError) as v:
  629. raise PyCMSError(v) from v
  630. def getProfileName(profile: _CmsProfileCompatible) -> str:
  631. """
  632. (pyCMS) Gets the internal product name for the given profile.
  633. If ``profile`` isn't a valid CmsProfile object or filename to a profile,
  634. a :exc:`PyCMSError` is raised If an error occurs while trying
  635. to obtain the name tag, a :exc:`PyCMSError` is raised.
  636. Use this function to obtain the INTERNAL name of the profile (stored
  637. in an ICC tag in the profile itself), usually the one used when the
  638. profile was originally created. Sometimes this tag also contains
  639. additional information supplied by the creator.
  640. :param profile: EITHER a valid CmsProfile object, OR a string of the
  641. filename of an ICC profile.
  642. :returns: A string containing the internal name of the profile as stored
  643. in an ICC tag.
  644. :exception PyCMSError:
  645. """
  646. try:
  647. # add an extra newline to preserve pyCMS compatibility
  648. if not isinstance(profile, ImageCmsProfile):
  649. profile = ImageCmsProfile(profile)
  650. # do it in python, not c.
  651. # // name was "%s - %s" (model, manufacturer) || Description ,
  652. # // but if the Model and Manufacturer were the same or the model
  653. # // was long, Just the model, in 1.x
  654. model = profile.profile.model
  655. manufacturer = profile.profile.manufacturer
  656. if not (model or manufacturer):
  657. return (profile.profile.profile_description or "") + "\n"
  658. if not manufacturer or (model and len(model) > 30):
  659. return f"{model}\n"
  660. return f"{model} - {manufacturer}\n"
  661. except (AttributeError, OSError, TypeError, ValueError) as v:
  662. raise PyCMSError(v) from v
  663. def getProfileInfo(profile: _CmsProfileCompatible) -> str:
  664. """
  665. (pyCMS) Gets the internal product information for the given profile.
  666. If ``profile`` isn't a valid CmsProfile object or filename to a profile,
  667. a :exc:`PyCMSError` is raised.
  668. If an error occurs while trying to obtain the info tag,
  669. a :exc:`PyCMSError` is raised.
  670. Use this function to obtain the information stored in the profile's
  671. info tag. This often contains details about the profile, and how it
  672. was created, as supplied by the creator.
  673. :param profile: EITHER a valid CmsProfile object, OR a string of the
  674. filename of an ICC profile.
  675. :returns: A string containing the internal profile information stored in
  676. an ICC tag.
  677. :exception PyCMSError:
  678. """
  679. try:
  680. if not isinstance(profile, ImageCmsProfile):
  681. profile = ImageCmsProfile(profile)
  682. # add an extra newline to preserve pyCMS compatibility
  683. # Python, not C. the white point bits weren't working well,
  684. # so skipping.
  685. # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
  686. description = profile.profile.profile_description
  687. cpright = profile.profile.copyright
  688. elements = [element for element in (description, cpright) if element]
  689. return "\r\n\r\n".join(elements) + "\r\n\r\n"
  690. except (AttributeError, OSError, TypeError, ValueError) as v:
  691. raise PyCMSError(v) from v
  692. def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
  693. """
  694. (pyCMS) Gets the copyright for the given profile.
  695. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  696. :exc:`PyCMSError` is raised.
  697. If an error occurs while trying to obtain the copyright tag,
  698. a :exc:`PyCMSError` is raised.
  699. Use this function to obtain the information stored in the profile's
  700. copyright tag.
  701. :param profile: EITHER a valid CmsProfile object, OR a string of the
  702. filename of an ICC profile.
  703. :returns: A string containing the internal profile information stored in
  704. an ICC tag.
  705. :exception PyCMSError:
  706. """
  707. try:
  708. # add an extra newline to preserve pyCMS compatibility
  709. if not isinstance(profile, ImageCmsProfile):
  710. profile = ImageCmsProfile(profile)
  711. return (profile.profile.copyright or "") + "\n"
  712. except (AttributeError, OSError, TypeError, ValueError) as v:
  713. raise PyCMSError(v) from v
  714. def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
  715. """
  716. (pyCMS) Gets the manufacturer for the given profile.
  717. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  718. :exc:`PyCMSError` is raised.
  719. If an error occurs while trying to obtain the manufacturer tag, a
  720. :exc:`PyCMSError` is raised.
  721. Use this function to obtain the information stored in the profile's
  722. manufacturer tag.
  723. :param profile: EITHER a valid CmsProfile object, OR a string of the
  724. filename of an ICC profile.
  725. :returns: A string containing the internal profile information stored in
  726. an ICC tag.
  727. :exception PyCMSError:
  728. """
  729. try:
  730. # add an extra newline to preserve pyCMS compatibility
  731. if not isinstance(profile, ImageCmsProfile):
  732. profile = ImageCmsProfile(profile)
  733. return (profile.profile.manufacturer or "") + "\n"
  734. except (AttributeError, OSError, TypeError, ValueError) as v:
  735. raise PyCMSError(v) from v
  736. def getProfileModel(profile: _CmsProfileCompatible) -> str:
  737. """
  738. (pyCMS) Gets the model for the given profile.
  739. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  740. :exc:`PyCMSError` is raised.
  741. If an error occurs while trying to obtain the model tag,
  742. a :exc:`PyCMSError` is raised.
  743. Use this function to obtain the information stored in the profile's
  744. model tag.
  745. :param profile: EITHER a valid CmsProfile object, OR a string of the
  746. filename of an ICC profile.
  747. :returns: A string containing the internal profile information stored in
  748. an ICC tag.
  749. :exception PyCMSError:
  750. """
  751. try:
  752. # add an extra newline to preserve pyCMS compatibility
  753. if not isinstance(profile, ImageCmsProfile):
  754. profile = ImageCmsProfile(profile)
  755. return (profile.profile.model or "") + "\n"
  756. except (AttributeError, OSError, TypeError, ValueError) as v:
  757. raise PyCMSError(v) from v
  758. def getProfileDescription(profile: _CmsProfileCompatible) -> str:
  759. """
  760. (pyCMS) Gets the description for the given profile.
  761. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  762. :exc:`PyCMSError` is raised.
  763. If an error occurs while trying to obtain the description tag,
  764. a :exc:`PyCMSError` is raised.
  765. Use this function to obtain the information stored in the profile's
  766. description tag.
  767. :param profile: EITHER a valid CmsProfile object, OR a string of the
  768. filename of an ICC profile.
  769. :returns: A string containing the internal profile information stored in an
  770. ICC tag.
  771. :exception PyCMSError:
  772. """
  773. try:
  774. # add an extra newline to preserve pyCMS compatibility
  775. if not isinstance(profile, ImageCmsProfile):
  776. profile = ImageCmsProfile(profile)
  777. return (profile.profile.profile_description or "") + "\n"
  778. except (AttributeError, OSError, TypeError, ValueError) as v:
  779. raise PyCMSError(v) from v
  780. def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
  781. """
  782. (pyCMS) Gets the default intent name for the given profile.
  783. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  784. :exc:`PyCMSError` is raised.
  785. If an error occurs while trying to obtain the default intent, a
  786. :exc:`PyCMSError` is raised.
  787. Use this function to determine the default (and usually best optimized)
  788. rendering intent for this profile. Most profiles support multiple
  789. rendering intents, but are intended mostly for one type of conversion.
  790. If you wish to use a different intent than returned, use
  791. ImageCms.isIntentSupported() to verify it will work first.
  792. :param profile: EITHER a valid CmsProfile object, OR a string of the
  793. filename of an ICC profile.
  794. :returns: Integer 0-3 specifying the default rendering intent for this
  795. profile.
  796. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  797. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  798. ImageCms.Intent.SATURATION = 2
  799. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  800. see the pyCMS documentation for details on rendering intents and what
  801. they do.
  802. :exception PyCMSError:
  803. """
  804. try:
  805. if not isinstance(profile, ImageCmsProfile):
  806. profile = ImageCmsProfile(profile)
  807. return profile.profile.rendering_intent
  808. except (AttributeError, OSError, TypeError, ValueError) as v:
  809. raise PyCMSError(v) from v
  810. def isIntentSupported(
  811. profile: _CmsProfileCompatible, intent: Intent, direction: Direction
  812. ) -> Literal[-1, 1]:
  813. """
  814. (pyCMS) Checks if a given intent is supported.
  815. Use this function to verify that you can use your desired
  816. ``intent`` with ``profile``, and that ``profile`` can be used for the
  817. input/output/proof profile as you desire.
  818. Some profiles are created specifically for one "direction", can cannot
  819. be used for others. Some profiles can only be used for certain
  820. rendering intents, so it's best to either verify this before trying
  821. to create a transform with them (using this function), or catch the
  822. potential :exc:`PyCMSError` that will occur if they don't
  823. support the modes you select.
  824. :param profile: EITHER a valid CmsProfile object, OR a string of the
  825. filename of an ICC profile.
  826. :param intent: Integer (0-3) specifying the rendering intent you wish to
  827. use with this profile
  828. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  829. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  830. ImageCms.Intent.SATURATION = 2
  831. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  832. see the pyCMS documentation for details on rendering intents and what
  833. they do.
  834. :param direction: Integer specifying if the profile is to be used for
  835. input, output, or proof
  836. INPUT = 0 (or use ImageCms.Direction.INPUT)
  837. OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
  838. PROOF = 2 (or use ImageCms.Direction.PROOF)
  839. :returns: 1 if the intent/direction are supported, -1 if they are not.
  840. :exception PyCMSError:
  841. """
  842. try:
  843. if not isinstance(profile, ImageCmsProfile):
  844. profile = ImageCmsProfile(profile)
  845. # FIXME: I get different results for the same data w. different
  846. # compilers. Bug in LittleCMS or in the binding?
  847. if profile.profile.is_intent_supported(intent, direction):
  848. return 1
  849. else:
  850. return -1
  851. except (AttributeError, OSError, TypeError, ValueError) as v:
  852. raise PyCMSError(v) from v