ImageCms.py 37 KB

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