ImageCms.py 40 KB

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