ImageCms.py 41 KB

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