ImageCms.py 36 KB

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