ImageCms.py 36 KB

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