1
0

ImageCms.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. if isinstance(profile, str):
  193. if sys.platform == "win32":
  194. profile_bytes_path = profile.encode()
  195. try:
  196. profile_bytes_path.decode("ascii")
  197. except UnicodeDecodeError:
  198. with open(profile, "rb") as f:
  199. self._set(core.profile_frombytes(f.read()))
  200. return
  201. self._set(core.profile_open(profile), profile)
  202. elif hasattr(profile, "read"):
  203. self._set(core.profile_frombytes(profile.read()))
  204. elif isinstance(profile, core.CmsProfile):
  205. self._set(profile)
  206. else:
  207. msg = "Invalid type for Profile" # type: ignore[unreachable]
  208. raise TypeError(msg)
  209. def _set(self, profile: core.CmsProfile, filename: str | None = None) -> None:
  210. self.profile = profile
  211. self.filename = filename
  212. self.product_name = None # profile.product_name
  213. self.product_info = None # profile.product_info
  214. def tobytes(self) -> bytes:
  215. """
  216. Returns the profile in a format suitable for embedding in
  217. saved images.
  218. :returns: a bytes object containing the ICC profile.
  219. """
  220. return core.profile_tobytes(self.profile)
  221. class ImageCmsTransform(Image.ImagePointHandler):
  222. """
  223. Transform. This can be used with the procedural API, or with the standard
  224. :py:func:`~PIL.Image.Image.point` method.
  225. Will return the output profile in the ``output.info['icc_profile']``.
  226. """
  227. def __init__(
  228. self,
  229. input: ImageCmsProfile,
  230. output: ImageCmsProfile,
  231. input_mode: str,
  232. output_mode: str,
  233. intent: Intent = Intent.PERCEPTUAL,
  234. proof: ImageCmsProfile | None = None,
  235. proof_intent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
  236. flags: Flags = Flags.NONE,
  237. ):
  238. supported_modes = (
  239. "RGB",
  240. "RGBA",
  241. "RGBX",
  242. "CMYK",
  243. "I;16",
  244. "I;16L",
  245. "I;16B",
  246. "YCbCr",
  247. "LAB",
  248. "L",
  249. "1",
  250. )
  251. for mode in (input_mode, output_mode):
  252. if mode not in supported_modes:
  253. deprecate(
  254. mode,
  255. 12,
  256. {
  257. "L;16": "I;16 or I;16L",
  258. "L:16B": "I;16B",
  259. "YCCA": "YCbCr",
  260. "YCC": "YCbCr",
  261. }.get(mode),
  262. )
  263. if proof is None:
  264. self.transform = core.buildTransform(
  265. input.profile, output.profile, input_mode, output_mode, intent, flags
  266. )
  267. else:
  268. self.transform = core.buildProofTransform(
  269. input.profile,
  270. output.profile,
  271. proof.profile,
  272. input_mode,
  273. output_mode,
  274. intent,
  275. proof_intent,
  276. flags,
  277. )
  278. # Note: inputMode and outputMode are for pyCMS compatibility only
  279. self.input_mode = self.inputMode = input_mode
  280. self.output_mode = self.outputMode = output_mode
  281. self.output_profile = output
  282. def point(self, im: Image.Image) -> Image.Image:
  283. return self.apply(im)
  284. def apply(self, im: Image.Image, imOut: Image.Image | None = None) -> Image.Image:
  285. if imOut is None:
  286. imOut = Image.new(self.output_mode, im.size, None)
  287. self.transform.apply(im.getim(), imOut.getim())
  288. imOut.info["icc_profile"] = self.output_profile.tobytes()
  289. return imOut
  290. def apply_in_place(self, im: Image.Image) -> Image.Image:
  291. if im.mode != self.output_mode:
  292. msg = "mode mismatch"
  293. raise ValueError(msg) # wrong output mode
  294. self.transform.apply(im.getim(), im.getim())
  295. im.info["icc_profile"] = self.output_profile.tobytes()
  296. return im
  297. def get_display_profile(handle: SupportsInt | None = None) -> ImageCmsProfile | None:
  298. """
  299. (experimental) Fetches the profile for the current display device.
  300. :returns: ``None`` if the profile is not known.
  301. """
  302. if sys.platform != "win32":
  303. return None
  304. from . import ImageWin # type: ignore[unused-ignore, unreachable]
  305. if isinstance(handle, ImageWin.HDC):
  306. profile = core.get_display_profile_win32(int(handle), 1)
  307. else:
  308. profile = core.get_display_profile_win32(int(handle or 0))
  309. if profile is None:
  310. return None
  311. return ImageCmsProfile(profile)
  312. # --------------------------------------------------------------------.
  313. # pyCMS compatible layer
  314. # --------------------------------------------------------------------.
  315. class PyCMSError(Exception):
  316. """(pyCMS) Exception class.
  317. This is used for all errors in the pyCMS API."""
  318. pass
  319. def profileToProfile(
  320. im: Image.Image,
  321. inputProfile: _CmsProfileCompatible,
  322. outputProfile: _CmsProfileCompatible,
  323. renderingIntent: Intent = Intent.PERCEPTUAL,
  324. outputMode: str | None = None,
  325. inPlace: bool = False,
  326. flags: Flags = Flags.NONE,
  327. ) -> Image.Image | None:
  328. """
  329. (pyCMS) Applies an ICC transformation to a given image, mapping from
  330. ``inputProfile`` to ``outputProfile``.
  331. If the input or output profiles specified are not valid filenames, a
  332. :exc:`PyCMSError` will be raised. If ``inPlace`` is ``True`` and
  333. ``outputMode != im.mode``, a :exc:`PyCMSError` will be raised.
  334. If an error occurs during application of the profiles,
  335. a :exc:`PyCMSError` will be raised.
  336. If ``outputMode`` is not a mode supported by the ``outputProfile`` (or by pyCMS),
  337. a :exc:`PyCMSError` will be raised.
  338. This function applies an ICC transformation to im from ``inputProfile``'s
  339. color space to ``outputProfile``'s color space using the specified rendering
  340. intent to decide how to handle out-of-gamut colors.
  341. ``outputMode`` can be used to specify that a color mode conversion is to
  342. be done using these profiles, but the specified profiles must be able
  343. to handle that mode. I.e., if converting im from RGB to CMYK using
  344. profiles, the input profile must handle RGB data, and the output
  345. profile must handle CMYK data.
  346. :param im: An open :py:class:`~PIL.Image.Image` object (i.e. Image.new(...)
  347. or Image.open(...), etc.)
  348. :param inputProfile: String, as a valid filename path to the ICC input
  349. profile you wish to use for this image, or a profile object
  350. :param outputProfile: String, as a valid filename path to the ICC output
  351. profile you wish to use for this image, or a profile object
  352. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  353. wish to use for the transform
  354. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  355. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  356. ImageCms.Intent.SATURATION = 2
  357. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  358. see the pyCMS documentation for details on rendering intents and what
  359. they do.
  360. :param outputMode: A valid PIL mode for the output image (i.e. "RGB",
  361. "CMYK", etc.). Note: if rendering the image "inPlace", outputMode
  362. MUST be the same mode as the input, or omitted completely. If
  363. omitted, the outputMode will be the same as the mode of the input
  364. image (im.mode)
  365. :param inPlace: Boolean. If ``True``, the original image is modified in-place,
  366. and ``None`` is returned. If ``False`` (default), a new
  367. :py:class:`~PIL.Image.Image` object is returned with the transform applied.
  368. :param flags: Integer (0-...) specifying additional flags
  369. :returns: Either None or a new :py:class:`~PIL.Image.Image` object, depending on
  370. the value of ``inPlace``
  371. :exception PyCMSError:
  372. """
  373. if outputMode is None:
  374. outputMode = im.mode
  375. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  376. msg = "renderingIntent must be an integer between 0 and 3"
  377. raise PyCMSError(msg)
  378. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  379. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  380. raise PyCMSError(msg)
  381. try:
  382. if not isinstance(inputProfile, ImageCmsProfile):
  383. inputProfile = ImageCmsProfile(inputProfile)
  384. if not isinstance(outputProfile, ImageCmsProfile):
  385. outputProfile = ImageCmsProfile(outputProfile)
  386. transform = ImageCmsTransform(
  387. inputProfile,
  388. outputProfile,
  389. im.mode,
  390. outputMode,
  391. renderingIntent,
  392. flags=flags,
  393. )
  394. if inPlace:
  395. transform.apply_in_place(im)
  396. imOut = None
  397. else:
  398. imOut = transform.apply(im)
  399. except (OSError, TypeError, ValueError) as v:
  400. raise PyCMSError(v) from v
  401. return imOut
  402. def getOpenProfile(
  403. profileFilename: str | SupportsRead[bytes] | core.CmsProfile,
  404. ) -> ImageCmsProfile:
  405. """
  406. (pyCMS) Opens an ICC profile file.
  407. The PyCMSProfile object can be passed back into pyCMS for use in creating
  408. transforms and such (as in ImageCms.buildTransformFromOpenProfiles()).
  409. If ``profileFilename`` is not a valid filename for an ICC profile,
  410. a :exc:`PyCMSError` will be raised.
  411. :param profileFilename: String, as a valid filename path to the ICC profile
  412. you wish to open, or a file-like object.
  413. :returns: A CmsProfile class object.
  414. :exception PyCMSError:
  415. """
  416. try:
  417. return ImageCmsProfile(profileFilename)
  418. except (OSError, TypeError, ValueError) as v:
  419. raise PyCMSError(v) from v
  420. def buildTransform(
  421. inputProfile: _CmsProfileCompatible,
  422. outputProfile: _CmsProfileCompatible,
  423. inMode: str,
  424. outMode: str,
  425. renderingIntent: Intent = Intent.PERCEPTUAL,
  426. flags: Flags = Flags.NONE,
  427. ) -> ImageCmsTransform:
  428. """
  429. (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
  430. ``outputProfile``. Use applyTransform to apply the transform to a given
  431. image.
  432. If the input or output profiles specified are not valid filenames, a
  433. :exc:`PyCMSError` will be raised. If an error occurs during creation
  434. of the transform, a :exc:`PyCMSError` will be raised.
  435. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
  436. (or by pyCMS), a :exc:`PyCMSError` will be raised.
  437. This function builds and returns an ICC transform from the ``inputProfile``
  438. to the ``outputProfile`` using the ``renderingIntent`` to determine what to do
  439. with out-of-gamut colors. It will ONLY work for converting images that
  440. are in ``inMode`` to images that are in ``outMode`` color format (PIL mode,
  441. i.e. "RGB", "RGBA", "CMYK", etc.).
  442. Building the transform is a fair part of the overhead in
  443. ImageCms.profileToProfile(), so if you're planning on converting multiple
  444. images using the same input/output settings, this can save you time.
  445. Once you have a transform object, it can be used with
  446. ImageCms.applyProfile() to convert images without the need to re-compute
  447. the lookup table for the transform.
  448. The reason pyCMS returns a class object rather than a handle directly
  449. to the transform is that it needs to keep track of the PIL input/output
  450. modes that the transform is meant for. These attributes are stored in
  451. the ``inMode`` and ``outMode`` attributes of the object (which can be
  452. manually overridden if you really want to, but I don't know of any
  453. time that would be of use, or would even work).
  454. :param inputProfile: String, as a valid filename path to the ICC input
  455. profile you wish to use for this transform, or a profile object
  456. :param outputProfile: String, as a valid filename path to the ICC output
  457. profile you wish to use for this transform, or a profile object
  458. :param inMode: String, as a valid PIL mode that the appropriate profile
  459. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  460. :param outMode: String, as a valid PIL mode that the appropriate profile
  461. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  462. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  463. wish to use for the transform
  464. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  465. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  466. ImageCms.Intent.SATURATION = 2
  467. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  468. see the pyCMS documentation for details on rendering intents and what
  469. they do.
  470. :param flags: Integer (0-...) specifying additional flags
  471. :returns: A CmsTransform class object.
  472. :exception PyCMSError:
  473. """
  474. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  475. msg = "renderingIntent must be an integer between 0 and 3"
  476. raise PyCMSError(msg)
  477. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  478. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  479. raise PyCMSError(msg)
  480. try:
  481. if not isinstance(inputProfile, ImageCmsProfile):
  482. inputProfile = ImageCmsProfile(inputProfile)
  483. if not isinstance(outputProfile, ImageCmsProfile):
  484. outputProfile = ImageCmsProfile(outputProfile)
  485. return ImageCmsTransform(
  486. inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags
  487. )
  488. except (OSError, TypeError, ValueError) as v:
  489. raise PyCMSError(v) from v
  490. def buildProofTransform(
  491. inputProfile: _CmsProfileCompatible,
  492. outputProfile: _CmsProfileCompatible,
  493. proofProfile: _CmsProfileCompatible,
  494. inMode: str,
  495. outMode: str,
  496. renderingIntent: Intent = Intent.PERCEPTUAL,
  497. proofRenderingIntent: Intent = Intent.ABSOLUTE_COLORIMETRIC,
  498. flags: Flags = Flags.SOFTPROOFING,
  499. ) -> ImageCmsTransform:
  500. """
  501. (pyCMS) Builds an ICC transform mapping from the ``inputProfile`` to the
  502. ``outputProfile``, but tries to simulate the result that would be
  503. obtained on the ``proofProfile`` device.
  504. If the input, output, or proof profiles specified are not valid
  505. filenames, a :exc:`PyCMSError` will be raised.
  506. If an error occurs during creation of the transform,
  507. a :exc:`PyCMSError` will be raised.
  508. If ``inMode`` or ``outMode`` are not a mode supported by the ``outputProfile``
  509. (or by pyCMS), a :exc:`PyCMSError` will be raised.
  510. This function builds and returns an ICC transform from the ``inputProfile``
  511. to the ``outputProfile``, but tries to simulate the result that would be
  512. obtained on the ``proofProfile`` device using ``renderingIntent`` and
  513. ``proofRenderingIntent`` to determine what to do with out-of-gamut
  514. colors. This is known as "soft-proofing". It will ONLY work for
  515. converting images that are in ``inMode`` to images that are in outMode
  516. color format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).
  517. Usage of the resulting transform object is exactly the same as with
  518. ImageCms.buildTransform().
  519. Proof profiling is generally used when using an output device to get a
  520. good idea of what the final printed/displayed image would look like on
  521. the ``proofProfile`` device when it's quicker and easier to use the
  522. output device for judging color. Generally, this means that the
  523. output device is a monitor, or a dye-sub printer (etc.), and the simulated
  524. device is something more expensive, complicated, or time consuming
  525. (making it difficult to make a real print for color judgement purposes).
  526. Soft-proofing basically functions by adjusting the colors on the
  527. output device to match the colors of the device being simulated. However,
  528. when the simulated device has a much wider gamut than the output
  529. device, you may obtain marginal results.
  530. :param inputProfile: String, as a valid filename path to the ICC input
  531. profile you wish to use for this transform, or a profile object
  532. :param outputProfile: String, as a valid filename path to the ICC output
  533. (monitor, usually) profile you wish to use for this transform, or a
  534. profile object
  535. :param proofProfile: String, as a valid filename path to the ICC proof
  536. profile you wish to use for this transform, or a profile object
  537. :param inMode: String, as a valid PIL mode that the appropriate profile
  538. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  539. :param outMode: String, as a valid PIL mode that the appropriate profile
  540. also supports (i.e. "RGB", "RGBA", "CMYK", etc.)
  541. :param renderingIntent: Integer (0-3) specifying the rendering intent you
  542. wish to use for the input->proof (simulated) transform
  543. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  544. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  545. ImageCms.Intent.SATURATION = 2
  546. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  547. see the pyCMS documentation for details on rendering intents and what
  548. they do.
  549. :param proofRenderingIntent: Integer (0-3) specifying the rendering intent
  550. you wish to use for proof->output transform
  551. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  552. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  553. ImageCms.Intent.SATURATION = 2
  554. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  555. see the pyCMS documentation for details on rendering intents and what
  556. they do.
  557. :param flags: Integer (0-...) specifying additional flags
  558. :returns: A CmsTransform class object.
  559. :exception PyCMSError:
  560. """
  561. if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):
  562. msg = "renderingIntent must be an integer between 0 and 3"
  563. raise PyCMSError(msg)
  564. if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):
  565. msg = f"flags must be an integer between 0 and {_MAX_FLAG}"
  566. raise PyCMSError(msg)
  567. try:
  568. if not isinstance(inputProfile, ImageCmsProfile):
  569. inputProfile = ImageCmsProfile(inputProfile)
  570. if not isinstance(outputProfile, ImageCmsProfile):
  571. outputProfile = ImageCmsProfile(outputProfile)
  572. if not isinstance(proofProfile, ImageCmsProfile):
  573. proofProfile = ImageCmsProfile(proofProfile)
  574. return ImageCmsTransform(
  575. inputProfile,
  576. outputProfile,
  577. inMode,
  578. outMode,
  579. renderingIntent,
  580. proofProfile,
  581. proofRenderingIntent,
  582. flags,
  583. )
  584. except (OSError, TypeError, ValueError) as v:
  585. raise PyCMSError(v) from v
  586. buildTransformFromOpenProfiles = buildTransform
  587. buildProofTransformFromOpenProfiles = buildProofTransform
  588. def applyTransform(
  589. im: Image.Image, transform: ImageCmsTransform, inPlace: bool = False
  590. ) -> Image.Image | None:
  591. """
  592. (pyCMS) Applies a transform to a given image.
  593. If ``im.mode != transform.input_mode``, a :exc:`PyCMSError` is raised.
  594. If ``inPlace`` is ``True`` and ``transform.input_mode != transform.output_mode``, a
  595. :exc:`PyCMSError` is raised.
  596. If ``im.mode``, ``transform.input_mode`` or ``transform.output_mode`` is not
  597. supported by pyCMSdll or the profiles you used for the transform, a
  598. :exc:`PyCMSError` is raised.
  599. If an error occurs while the transform is being applied,
  600. a :exc:`PyCMSError` is raised.
  601. This function applies a pre-calculated transform (from
  602. ImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())
  603. to an image. The transform can be used for multiple images, saving
  604. considerable calculation time if doing the same conversion multiple times.
  605. If you want to modify im in-place instead of receiving a new image as
  606. the return value, set ``inPlace`` to ``True``. This can only be done if
  607. ``transform.input_mode`` and ``transform.output_mode`` are the same, because we
  608. can't change the mode in-place (the buffer sizes for some modes are
  609. different). The default behavior is to return a new :py:class:`~PIL.Image.Image`
  610. object of the same dimensions in mode ``transform.output_mode``.
  611. :param im: An :py:class:`~PIL.Image.Image` object, and ``im.mode`` must be the same
  612. as the ``input_mode`` supported by the transform.
  613. :param transform: A valid CmsTransform class object
  614. :param inPlace: Bool. If ``True``, ``im`` is modified in place and ``None`` is
  615. returned, if ``False``, a new :py:class:`~PIL.Image.Image` object with the
  616. transform applied is returned (and ``im`` is not changed). The default is
  617. ``False``.
  618. :returns: Either ``None``, or a new :py:class:`~PIL.Image.Image` object,
  619. depending on the value of ``inPlace``. The profile will be returned in
  620. the image's ``info['icc_profile']``.
  621. :exception PyCMSError:
  622. """
  623. try:
  624. if inPlace:
  625. transform.apply_in_place(im)
  626. imOut = None
  627. else:
  628. imOut = transform.apply(im)
  629. except (TypeError, ValueError) as v:
  630. raise PyCMSError(v) from v
  631. return imOut
  632. def createProfile(
  633. colorSpace: Literal["LAB", "XYZ", "sRGB"], colorTemp: SupportsFloat = 0
  634. ) -> core.CmsProfile:
  635. """
  636. (pyCMS) Creates a profile.
  637. If colorSpace not in ``["LAB", "XYZ", "sRGB"]``,
  638. a :exc:`PyCMSError` is raised.
  639. If using LAB and ``colorTemp`` is not a positive integer,
  640. a :exc:`PyCMSError` is raised.
  641. If an error occurs while creating the profile,
  642. a :exc:`PyCMSError` is raised.
  643. Use this function to create common profiles on-the-fly instead of
  644. having to supply a profile on disk and knowing the path to it. It
  645. returns a normal CmsProfile object that can be passed to
  646. ImageCms.buildTransformFromOpenProfiles() to create a transform to apply
  647. to images.
  648. :param colorSpace: String, the color space of the profile you wish to
  649. create.
  650. Currently only "LAB", "XYZ", and "sRGB" are supported.
  651. :param colorTemp: Positive number for the white point for the profile, in
  652. degrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50
  653. illuminant if omitted (5000k). colorTemp is ONLY applied to LAB
  654. profiles, and is ignored for XYZ and sRGB.
  655. :returns: A CmsProfile class object
  656. :exception PyCMSError:
  657. """
  658. if colorSpace not in ["LAB", "XYZ", "sRGB"]:
  659. msg = (
  660. f"Color space not supported for on-the-fly profile creation ({colorSpace})"
  661. )
  662. raise PyCMSError(msg)
  663. if colorSpace == "LAB":
  664. try:
  665. colorTemp = float(colorTemp)
  666. except (TypeError, ValueError) as e:
  667. msg = f'Color temperature must be numeric, "{colorTemp}" not valid'
  668. raise PyCMSError(msg) from e
  669. try:
  670. return core.createProfile(colorSpace, colorTemp)
  671. except (TypeError, ValueError) as v:
  672. raise PyCMSError(v) from v
  673. def getProfileName(profile: _CmsProfileCompatible) -> str:
  674. """
  675. (pyCMS) Gets the internal product name for the given profile.
  676. If ``profile`` isn't a valid CmsProfile object or filename to a profile,
  677. a :exc:`PyCMSError` is raised If an error occurs while trying
  678. to obtain the name tag, a :exc:`PyCMSError` is raised.
  679. Use this function to obtain the INTERNAL name of the profile (stored
  680. in an ICC tag in the profile itself), usually the one used when the
  681. profile was originally created. Sometimes this tag also contains
  682. additional information supplied by the creator.
  683. :param profile: EITHER a valid CmsProfile object, OR a string of the
  684. filename of an ICC profile.
  685. :returns: A string containing the internal name of the profile as stored
  686. in an ICC tag.
  687. :exception PyCMSError:
  688. """
  689. try:
  690. # add an extra newline to preserve pyCMS compatibility
  691. if not isinstance(profile, ImageCmsProfile):
  692. profile = ImageCmsProfile(profile)
  693. # do it in python, not c.
  694. # // name was "%s - %s" (model, manufacturer) || Description ,
  695. # // but if the Model and Manufacturer were the same or the model
  696. # // was long, Just the model, in 1.x
  697. model = profile.profile.model
  698. manufacturer = profile.profile.manufacturer
  699. if not (model or manufacturer):
  700. return (profile.profile.profile_description or "") + "\n"
  701. if not manufacturer or (model and len(model) > 30):
  702. return f"{model}\n"
  703. return f"{model} - {manufacturer}\n"
  704. except (AttributeError, OSError, TypeError, ValueError) as v:
  705. raise PyCMSError(v) from v
  706. def getProfileInfo(profile: _CmsProfileCompatible) -> str:
  707. """
  708. (pyCMS) Gets the internal product information for the given profile.
  709. If ``profile`` isn't a valid CmsProfile object or filename to a profile,
  710. a :exc:`PyCMSError` is raised.
  711. If an error occurs while trying to obtain the info tag,
  712. a :exc:`PyCMSError` is raised.
  713. Use this function to obtain the information stored in the profile's
  714. info tag. This often contains details about the profile, and how it
  715. was created, as supplied by the creator.
  716. :param profile: EITHER a valid CmsProfile object, OR a string of the
  717. filename of an ICC profile.
  718. :returns: A string containing the internal profile information stored in
  719. an ICC tag.
  720. :exception PyCMSError:
  721. """
  722. try:
  723. if not isinstance(profile, ImageCmsProfile):
  724. profile = ImageCmsProfile(profile)
  725. # add an extra newline to preserve pyCMS compatibility
  726. # Python, not C. the white point bits weren't working well,
  727. # so skipping.
  728. # info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepoint
  729. description = profile.profile.profile_description
  730. cpright = profile.profile.copyright
  731. elements = [element for element in (description, cpright) if element]
  732. return "\r\n\r\n".join(elements) + "\r\n\r\n"
  733. except (AttributeError, OSError, TypeError, ValueError) as v:
  734. raise PyCMSError(v) from v
  735. def getProfileCopyright(profile: _CmsProfileCompatible) -> str:
  736. """
  737. (pyCMS) Gets the copyright for the given profile.
  738. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  739. :exc:`PyCMSError` is raised.
  740. If an error occurs while trying to obtain the copyright tag,
  741. a :exc:`PyCMSError` is raised.
  742. Use this function to obtain the information stored in the profile's
  743. copyright tag.
  744. :param profile: EITHER a valid CmsProfile object, OR a string of the
  745. filename of an ICC profile.
  746. :returns: A string containing the internal profile information stored in
  747. an ICC tag.
  748. :exception PyCMSError:
  749. """
  750. try:
  751. # add an extra newline to preserve pyCMS compatibility
  752. if not isinstance(profile, ImageCmsProfile):
  753. profile = ImageCmsProfile(profile)
  754. return (profile.profile.copyright or "") + "\n"
  755. except (AttributeError, OSError, TypeError, ValueError) as v:
  756. raise PyCMSError(v) from v
  757. def getProfileManufacturer(profile: _CmsProfileCompatible) -> str:
  758. """
  759. (pyCMS) Gets the manufacturer for the given profile.
  760. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  761. :exc:`PyCMSError` is raised.
  762. If an error occurs while trying to obtain the manufacturer tag, a
  763. :exc:`PyCMSError` is raised.
  764. Use this function to obtain the information stored in the profile's
  765. manufacturer tag.
  766. :param profile: EITHER a valid CmsProfile object, OR a string of the
  767. filename of an ICC profile.
  768. :returns: A string containing the internal profile information stored in
  769. an ICC tag.
  770. :exception PyCMSError:
  771. """
  772. try:
  773. # add an extra newline to preserve pyCMS compatibility
  774. if not isinstance(profile, ImageCmsProfile):
  775. profile = ImageCmsProfile(profile)
  776. return (profile.profile.manufacturer or "") + "\n"
  777. except (AttributeError, OSError, TypeError, ValueError) as v:
  778. raise PyCMSError(v) from v
  779. def getProfileModel(profile: _CmsProfileCompatible) -> str:
  780. """
  781. (pyCMS) Gets the model for the given profile.
  782. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  783. :exc:`PyCMSError` is raised.
  784. If an error occurs while trying to obtain the model tag,
  785. a :exc:`PyCMSError` is raised.
  786. Use this function to obtain the information stored in the profile's
  787. model tag.
  788. :param profile: EITHER a valid CmsProfile object, OR a string of the
  789. filename of an ICC profile.
  790. :returns: A string containing the internal profile information stored in
  791. an ICC tag.
  792. :exception PyCMSError:
  793. """
  794. try:
  795. # add an extra newline to preserve pyCMS compatibility
  796. if not isinstance(profile, ImageCmsProfile):
  797. profile = ImageCmsProfile(profile)
  798. return (profile.profile.model or "") + "\n"
  799. except (AttributeError, OSError, TypeError, ValueError) as v:
  800. raise PyCMSError(v) from v
  801. def getProfileDescription(profile: _CmsProfileCompatible) -> str:
  802. """
  803. (pyCMS) Gets the description for the given profile.
  804. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  805. :exc:`PyCMSError` is raised.
  806. If an error occurs while trying to obtain the description tag,
  807. a :exc:`PyCMSError` is raised.
  808. Use this function to obtain the information stored in the profile's
  809. description tag.
  810. :param profile: EITHER a valid CmsProfile object, OR a string of the
  811. filename of an ICC profile.
  812. :returns: A string containing the internal profile information stored in an
  813. ICC tag.
  814. :exception PyCMSError:
  815. """
  816. try:
  817. # add an extra newline to preserve pyCMS compatibility
  818. if not isinstance(profile, ImageCmsProfile):
  819. profile = ImageCmsProfile(profile)
  820. return (profile.profile.profile_description or "") + "\n"
  821. except (AttributeError, OSError, TypeError, ValueError) as v:
  822. raise PyCMSError(v) from v
  823. def getDefaultIntent(profile: _CmsProfileCompatible) -> int:
  824. """
  825. (pyCMS) Gets the default intent name for the given profile.
  826. If ``profile`` isn't a valid CmsProfile object or filename to a profile, a
  827. :exc:`PyCMSError` is raised.
  828. If an error occurs while trying to obtain the default intent, a
  829. :exc:`PyCMSError` is raised.
  830. Use this function to determine the default (and usually best optimized)
  831. rendering intent for this profile. Most profiles support multiple
  832. rendering intents, but are intended mostly for one type of conversion.
  833. If you wish to use a different intent than returned, use
  834. ImageCms.isIntentSupported() to verify it will work first.
  835. :param profile: EITHER a valid CmsProfile object, OR a string of the
  836. filename of an ICC profile.
  837. :returns: Integer 0-3 specifying the default rendering intent for this
  838. profile.
  839. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  840. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  841. ImageCms.Intent.SATURATION = 2
  842. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  843. see the pyCMS documentation for details on rendering intents and what
  844. they do.
  845. :exception PyCMSError:
  846. """
  847. try:
  848. if not isinstance(profile, ImageCmsProfile):
  849. profile = ImageCmsProfile(profile)
  850. return profile.profile.rendering_intent
  851. except (AttributeError, OSError, TypeError, ValueError) as v:
  852. raise PyCMSError(v) from v
  853. def isIntentSupported(
  854. profile: _CmsProfileCompatible, intent: Intent, direction: Direction
  855. ) -> Literal[-1, 1]:
  856. """
  857. (pyCMS) Checks if a given intent is supported.
  858. Use this function to verify that you can use your desired
  859. ``intent`` with ``profile``, and that ``profile`` can be used for the
  860. input/output/proof profile as you desire.
  861. Some profiles are created specifically for one "direction", can cannot
  862. be used for others. Some profiles can only be used for certain
  863. rendering intents, so it's best to either verify this before trying
  864. to create a transform with them (using this function), or catch the
  865. potential :exc:`PyCMSError` that will occur if they don't
  866. support the modes you select.
  867. :param profile: EITHER a valid CmsProfile object, OR a string of the
  868. filename of an ICC profile.
  869. :param intent: Integer (0-3) specifying the rendering intent you wish to
  870. use with this profile
  871. ImageCms.Intent.PERCEPTUAL = 0 (DEFAULT)
  872. ImageCms.Intent.RELATIVE_COLORIMETRIC = 1
  873. ImageCms.Intent.SATURATION = 2
  874. ImageCms.Intent.ABSOLUTE_COLORIMETRIC = 3
  875. see the pyCMS documentation for details on rendering intents and what
  876. they do.
  877. :param direction: Integer specifying if the profile is to be used for
  878. input, output, or proof
  879. INPUT = 0 (or use ImageCms.Direction.INPUT)
  880. OUTPUT = 1 (or use ImageCms.Direction.OUTPUT)
  881. PROOF = 2 (or use ImageCms.Direction.PROOF)
  882. :returns: 1 if the intent/direction are supported, -1 if they are not.
  883. :exception PyCMSError:
  884. """
  885. try:
  886. if not isinstance(profile, ImageCmsProfile):
  887. profile = ImageCmsProfile(profile)
  888. # FIXME: I get different results for the same data w. different
  889. # compilers. Bug in LittleCMS or in the binding?
  890. if profile.profile.is_intent_supported(intent, direction):
  891. return 1
  892. else:
  893. return -1
  894. except (AttributeError, OSError, TypeError, ValueError) as v:
  895. raise PyCMSError(v) from v
  896. def versions() -> tuple[str, str | None, str, str]:
  897. """
  898. (pyCMS) Fetches versions.
  899. """
  900. deprecate(
  901. "PIL.ImageCms.versions()",
  902. 12,
  903. '(PIL.features.version("littlecms2"), sys.version, PIL.__version__)',
  904. )
  905. return _VERSION, core.littlecms_version, sys.version.split()[0], __version__